2018-11-27 05:23:30 +08:00
---
title: Build web APIs with ASP.NET Core and MongoDB
2018-12-05 11:57:06 +08:00
author: prkhandelwal
2018-11-27 05:23:30 +08:00
description: This tutorial demonstrates how to build an ASP.NET Core web API using a MongoDB NoSQL database.
ms.author: scaddie
2018-12-07 12:29:00 +08:00
ms.custom: mvc,seodec18
2018-11-30 00:07:00 +08:00
ms.date: 11/29/2018
2018-11-27 05:23:30 +08:00
uid: tutorials/first-mongo-app
---
# Create a web API with ASP.NET Core and MongoDB
2018-11-27 06:20:16 +08:00
By [Pratik Khandelwal ](https://twitter.com/K2Prk ) and [Scott Addie ](https://twitter.com/Scott_Addie )
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a [MongoDB ](https://www.mongodb.com/what-is-mongodb ) NoSQL database.
2018-11-27 05:23:30 +08:00
In this tutorial, you learn how to:
> [!div class="checklist"]
> * Configure MongoDB
> * Create a MongoDB database
> * Define a MongoDB collection and schema
> * Perform MongoDB CRUD operations from a web API
2018-11-27 06:20:16 +08:00
[View or download sample code ](https://github.com/aspnet/Docs/tree/master/aspnetcore/tutorials/first-mongo-app/sample ) ([how to download](xref:index#how-to-download-a-sample))
2018-11-27 05:23:30 +08:00
## Prerequisites
2018-11-29 06:14:03 +08:00
# [Visual Studio](#tab/visual-studio)
* [.NET Core SDK 2.2 or later ](https://www.microsoft.com/net/download/all )
2018-11-30 00:07:00 +08:00
* [Visual Studio 2017 version 15.9 or later ](https://www.visualstudio.com/downloads/ ) with the **ASP.NET and web development** workload
2018-11-29 06:14:03 +08:00
* [MongoDB ](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/ )
# [Visual Studio Code](#tab/visual-studio-code)
* [.NET Core SDK 2.2 or later ](https://www.microsoft.com/net/download/all )
* [Visual Studio Code ](https://code.visualstudio.com/download )
* [C# for Visual Studio Code ](https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp )
* [MongoDB ](https://docs.mongodb.com/manual/administration/install-community/ )
# [Visual Studio for Mac](#tab/visual-studio-mac)
* [.NET Core SDK 2.2 or later ](https://www.microsoft.com/net/download/all )
* [Visual Studio for Mac version 7.7 or later ](https://www.visualstudio.com/downloads/ )
* [MongoDB ](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/ )
---
2018-11-27 05:23:30 +08:00
## Configure MongoDB
If using Windows, MongoDB is installed at *C:\Program Files\MongoDB* by default. Add *C:\Program Files\MongoDB\Server\<version_number>\bin* to the `Path` environment variable. This change enables MongoDB access from anywhere on your development machine.
2018-11-28 10:36:18 +08:00
Use the mongo Shell in the following steps to create a database, make collections, and store documents. For more information on mongo Shell commands, see [Working with the mongo Shell ](https://docs.mongodb.com/manual/mongo/#working-with-the-mongo-shell ).
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
1. Choose a directory on your development machine for storing the data. For example, *C:\BooksData* on Windows. Create the directory if it doesn't exist. The mongo Shell doesn't create new directories.
1. Open a command shell. Run the following command to connect to MongoDB on default port 27017. Remember to replace `<data_directory_path>` with the directory you chose in the previous step.
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
```console
2018-11-28 10:36:18 +08:00
mongod --dbpath < data_directory_path >
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
1. Open another command shell instance. Connect to the default test database by running the following command:
2018-11-27 06:20:16 +08:00
```console
mongo
```
2018-11-27 05:23:30 +08:00
1. Run the following in a command shell:
2018-11-27 06:20:16 +08:00
```console
use BookstoreDb
```
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
If it doesn't already exist, a database named *BookstoreDb* is created. If the database does exist, its connection is opened for transactions.
2018-11-27 05:23:30 +08:00
1. Create a `Books` collection using following command:
2018-11-27 06:20:16 +08:00
```console
db.createCollection('Books')
```
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The following result is displayed:
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
```console
2018-11-27 06:20:16 +08:00
{ "ok" : 1 }
```
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
1. Define a schema for the `Books` collection and insert two documents using the following command:
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
```console
2018-11-28 10:36:18 +08:00
db.Books.insertMany([{'Name':'Design Patterns','Price':54.93,'Category':'Computers','Author':'Ralph Johnson'}, {'Name':'Clean Code','Price':43.15,'Category':'Computers','Author':'Robert C. Martin'}])
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The following result is displayed:
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
```console
2018-11-28 10:36:18 +08:00
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5bfd996f7b8e48dc15ff215d"),
ObjectId("5bfd996f7b8e48dc15ff215e")
]
}
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
1. View the documents in the database using the following command:
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
```console
2018-11-28 10:36:18 +08:00
db.Books.find({}).pretty()
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The following result is displayed:
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
```console
{
"_id" : ObjectId("5bfd996f7b8e48dc15ff215d"),
"Name" : "Design Patterns",
"Price" : 54.93,
"Category" : "Computers",
"Author" : "Ralph Johnson"
}
{
"_id" : ObjectId("5bfd996f7b8e48dc15ff215e"),
"Name" : "Clean Code",
"Price" : 43.15,
"Category" : "Computers",
"Author" : "Robert C. Martin"
}
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
The schema adds an autogenerated `_id` property of type `ObjectId` for each document.
2018-11-27 05:23:30 +08:00
The database is ready. You can start creating the ASP.NET Core web API.
## Create the ASP.NET Core web API project
2018-11-29 06:14:03 +08:00
# [Visual Studio](#tab/visual-studio)
1. Go to **File** > **New** > **Project** .
1. Select **ASP.NET Core Web Application** , name the project *BooksApi* , and click **OK** .
2018-11-27 06:20:16 +08:00
1. Select the ** .NET Core** target framework and **ASP.NET Core 2.1** . Select the **API** project template, and click **OK** :
2018-11-27 05:23:30 +08:00
1. In the **Package Manager Console** window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:
2018-11-27 06:20:16 +08:00
```powershell
2018-11-28 10:36:18 +08:00
Install-Package MongoDB.Driver -Version 2.7.2
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
# [Visual Studio Code](#tab/visual-studio-code)
1. Run the following commands in a command shell:
```console
dotnet new webapi -o BooksApi
code BooksApi
```
A new ASP.NET Core web API project targeting .NET Core is generated and opened in Visual Studio Code.
1. Click **Yes** when the *Required assets to build and debug are missing from 'BooksApi'. Add them?* notification appears.
1. Open **Integrated Terminal** and navigate to the project root. Run the following command to install the .NET driver for MongoDB:
```console
dotnet add BooksApi.csproj package MongoDB.Driver -v 2.7.2
```
# [Visual Studio for Mac](#tab/visual-studio-mac)
1. Go to **File** > **New Solution** > ** .NET Core** > **App** .
1. Select the **ASP.NET Core Web API** C# project template, and click **Next** .
1. Select ** .NET Core 2.2** from the **Target Framework** drop-down list, and click **Next** .
1. Enter *BooksApi* for the **Project Name** , and click **Create** .
1. In the **Solution** pad, right-click the project's **Dependencies** node and select **Add Packages** .
1. Enter *MongoDB.Driver* in the search box, select the *MongoDB.Driver* package, and click **Add Package** .
1. Click the **Accept** button in the **License Acceptance** dialog.
---
2018-11-27 05:23:30 +08:00
## Add a model
2018-11-29 06:14:03 +08:00
1. Add a *Models* directory to the project root.
1. Add a `Book` class to the *Models* directory with the following code:
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/Models/Book.cs )]
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
In the preceding class, the `Id` property is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection. Other properties in the class are decorated with the `[BsonElement]` attribute. The attribute's value represents the property name in the MongoDB collection.
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
## Add a CRUD operations class
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
1. Add a *Services* directory to the project root.
1. Add a `BookService` class to the *Services* directory with the following code:
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/Services/BookService.cs?name=snippet_BookServiceClass )]
2018-11-28 10:36:18 +08:00
1. Add the MongoDB connection string to *appsettings.json* :
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/appsettings.json?highlight=2-4 )]
2018-11-28 10:36:18 +08:00
The preceding `BookstoreDb` property is accessed in the `BookService` class constructor.
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
1. In `Startup.ConfigureServices` , register the `BookService` class with the Dependency Injection system:
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/Startup.cs?name=snippet_ConfigureServices&highlight=3 )]
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The preceding service registration is necessary to support constructor injection in consuming classes.
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The `BookService` class uses the following `MongoDB.Driver` members to perform CRUD operations against the database:
* `MongoClient` – Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string:
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/Services/BookService.cs?name=snippet_BookServiceConstructor&highlight=3 )]
2018-11-27 06:20:16 +08:00
* `IMongoDatabase` – Represents the Mongo database for performing operations. This tutorial uses the generic `GetCollection<T>(collection)` method on the interface to gain access to data in a specific collection. CRUD operations can be performed against the collection after this method is called. In the `GetCollection<T>(collection)` method call:
* `collection` represents the collection name.
* `T` represents the CLR object type stored in the collection.
`GetCollection<T>(collection)` returns a `MongoCollection` object representing the collection. In this tutorial, the following methods are invoked on the collection:
2018-11-28 10:36:18 +08:00
* `Find<T>` – Returns all documents in the collection matching the provided search criteria.
* `InsertOne` – Inserts the provided object as a new document in the collection.
* `ReplaceOne` – Replaces the single document matching the provided search criteria with the provided object.
* `DeleteOne` – Deletes a single document matching the provided search criteria.
2018-11-27 05:23:30 +08:00
## Add a controller
2018-11-29 06:14:03 +08:00
1. Add a `BooksController` class to the *Controllers* directory with the following code:
2018-11-27 05:23:30 +08:00
2018-11-29 06:14:03 +08:00
[!code-csharp[ ](first-mongo-app/sample/BooksApi/Controllers/BooksController.cs )]
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
The preceding web API controller:
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
* Uses the `BookService` class to perform CRUD operations.
* Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
2018-11-27 05:23:30 +08:00
1. Build and run the app.
2018-11-28 10:36:18 +08:00
1. Navigate to `http://localhost:<port>/api/books` in your browser. The following JSON response is displayed:
2018-11-27 05:23:30 +08:00
2018-11-27 06:20:16 +08:00
```json
2018-11-28 10:36:18 +08:00
[
{
"id":"5bfd996f7b8e48dc15ff215d",
"bookName":"Design Patterns",
"price":54.93,
"category":"Computers",
"author":"Ralph Johnson"
},
{
"id":"5bfd996f7b8e48dc15ff215e",
"bookName":"Clean Code",
"price":43.15,
"category":"Computers",
"author":"Robert C. Martin"
}
]
2018-11-27 06:20:16 +08:00
```
2018-11-27 05:23:30 +08:00
2018-11-28 10:36:18 +08:00
## Next steps
For more information on building ASP.NET Core web APIs, see the following resources:
* < xref:web-api / index >
* < xref:web-api / action-return-types >