AspNetCore.Docs/aspnetcore/tutorials/first-mongo-app.md

11 KiB
Raw Blame History

title author description ms.author ms.custom ms.date uid
Build web APIs with ASP.NET Core and MongoDB prkhandelwal This tutorial demonstrates how to build an ASP.NET Core web API using a MongoDB NoSQL database. scaddie mvc, seodec18 01/31/2019 tutorials/first-mongo-app

Create a web API with ASP.NET Core and MongoDB

By Pratik Khandelwal and Scott Addie

This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.

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

View or download sample code (how to download)

Prerequisites

Visual Studio

Visual Studio Code

Visual Studio for Mac


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.

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.

  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.

  2. 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.

    mongod --dbpath <data_directory_path>
    
  3. Open another command shell instance. Connect to the default test database by running the following command:

    mongo
    
  4. Run the following in a command shell:

    use BookstoreDb
    

    If it doesn't already exist, a database named BookstoreDb is created. If the database does exist, its connection is opened for transactions.

  5. Create a Books collection using following command:

    db.createCollection('Books')
    

    The following result is displayed:

    { "ok" : 1 }
    
  6. Define a schema for the Books collection and insert two documents using the following command:

    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'}])
    

    The following result is displayed:

    {
      "acknowledged" : true,
      "insertedIds" : [
        ObjectId("5bfd996f7b8e48dc15ff215d"),
        ObjectId("5bfd996f7b8e48dc15ff215e")
      ]
    }
    
  7. View the documents in the database using the following command:

    db.Books.find({}).pretty()
    

    The following result is displayed:

    {
      "_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"
    }
    

    The schema adds an autogenerated _id property of type ObjectId for each document.

The database is ready. You can start creating the ASP.NET Core web API.

Create the ASP.NET Core web API project

Visual Studio

  1. Go to File > New > Project.

  2. Select ASP.NET Core Web Application, name the project BooksApi, and click OK.

  3. Select the .NET Core target framework and ASP.NET Core 2.2. Select the API project template, and click OK:

  4. Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:

    Install-Package MongoDB.Driver -Version {VERSION}
    

Visual Studio Code

  1. Run the following commands in a command shell:

    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.

  2. Click Yes when the Required assets to build and debug are missing from 'BooksApi'. Add them? notification appears.

  3. Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. Open Integrated Terminal and navigate to the project root. Run the following command to install the .NET driver for MongoDB:

    dotnet add BooksApi.csproj package MongoDB.Driver -v {VERSION}
    

Visual Studio for Mac

  1. Go to File > New Solution > .NET Core > App.
  2. Select the ASP.NET Core Web API C# project template, and click Next.
  3. Select .NET Core 2.2 from the Target Framework drop-down list, and click Next.
  4. Enter BooksApi for the Project Name, and click Create.
  5. In the Solution pad, right-click the project's Dependencies node and select Add Packages.
  6. Enter MongoDB.Driver in the search box, select the MongoDB.Driver package, and click Add Package.
  7. Click the Accept button in the License Acceptance dialog.

Add a model

  1. Add a Models directory to the project root.

  2. Add a Book class to the Models directory with the following code:

    [!code-csharp]

In the preceding class, the Id property:

  • Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
  • Is annotated with [BsonId] to designate this property as the document's primary key.
  • Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type string instead of ObjectId. Mongo handles the conversion from string to ObjectId.

Other properties in the class are annotated with the [BsonElement] attribute. The attribute's value represents the property name in the MongoDB collection.

Add a CRUD operations class

  1. Add a Services directory to the project root.

  2. Add a BookService class to the Services directory with the following code:

    [!code-csharp]

  3. Add the MongoDB connection string to appsettings.json:

    [!code-csharp]

    The preceding BookstoreDb property is accessed in the BookService class constructor.

  4. In Startup.ConfigureServices, register the BookService class with the Dependency Injection system:

    [!code-csharp]

    The preceding service registration is necessary to support constructor injection in consuming classes.

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:

    [!code-csharp]

  • 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:

  • 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.

Add a controller

  1. Add a BooksController class to the Controllers directory with the following code:

    [!code-csharp]

    The preceding web API controller:

    • Uses the BookService class to perform CRUD operations.
    • Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
  2. Build and run the app.

  3. Navigate to http://localhost:<port>/api/books in your browser. The following JSON response is displayed:

    [
      {
        "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"
      }
    ]
    

Next steps

For more information on building ASP.NET Core web APIs, see the following resources: