ASP.NET Core 8: Create a API with ASP.NET Core to Perform CRUD Operations with MongoDB

In this article, we will see the use of MongoDB database client in ASP.NET Core API to perform CRUD Operations. In the categories of building data collections applications we need to use a large size NoSQL Database. The MongoDB database is one of the powerful NoSQL databases data offers the large scale data in the form of JSON documents. The data collection applications collect data from various front-end applications like We Apps, Mobile, Browser Apps, etc. Across all such applications we need to use powerful server-side data collection APIs those who will connect to MongoDB database easily and provide a simplified mechanism for performing CRUD Operations, the ASP.NET Core is such a powerful but an easy technology of building APIs for modern apps. The ASP.NET Core uses the MongoDB.Driver NuGet package that provides set of useful classes to access MongoDB database for performing CRUD operations. Figure 1 will provide an idea of implementation of the application.



Figure 1: The ASP.NET Core API access MongoDB Database

To connect with MongoDB database we need to install the MongoDB locally or use Docker image of MongoDB to create database and collections. Use the this link  to download MongoDB or use the Docker image to download using the following command

docker pull mongo

Download and install Mongodb Compass to interact with the MongoDB database so that we can create Database and collection. The MongoDB compass can be downloaded from this ink

Start the MongoDB Server. If you are using Docker image for the MongoDB Database, then run the image as shown in Figure 2



Figure 2: Running MongoDB Image in Docker

Open the MongoDB Compass and create Publication database and Novel collection as shown in Figure 3



Figure 3: Database and Collection 

 So far we have created database and collection. Now, lets create the ASP.NET Core Applciation.

Step 1: Create a new ASP.NET Core API project targeted to .NET 8 and name it Core_API_MongoDb. In this project, add MongoDB.Driver package. This package have some of the following types

  • MongoClient: This is used to connect to the MongoDB instance based on the connection string. This class manages all the operations with the database. The GetDatabase() method using which the database is accessed for performing operations. This method returns IMongoDatabase type. This type has the GetCollection() method to connect with the collection in the database based on the collection name. This method returns IMongoCollection type.    
  • IMongoCollection: This type contains methods for performing CRUD operations like, Find(), InsertOneAsync(), ReplaceOneAsync(), DeleteOneAsync(), etc.
Step 2: Open appsettings.json and add the database settings in it as shown n Listing 1 that define database name, collection name, etc.

  "DatabaseSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "Publication",
    "CollectionName": "Novels"
  },

Listing 1: The Database Settings

Step 2: In the project, add the Models folder and add a new class file in it named Nodel.cs. In this file, add the code as shown in Listing 2.

 public class Novel
 {
     [BsonId]
     [BsonRepresentation(BsonType.ObjectId)]
     public string? Id { get; set; }
     public string? NovelName { get; set; }
     public string? Author { get; set; }
     public string? Category { get; set; }
     public string? Description { get; set; }
     public int Price { get; set; }
 }

Listing 2: The Novel class
 
We have added this class so that we can create a collection of various Novels and save them in to the Publishing database. The class in Listing 2 have following specifications.
  • Annotation with [BsonId] is used to make the Id property the document's primary key.
  • Annotation with [BsonRepresentation(BsonType.ObjectId)] allows passing the parameter as type string instead of an ObjectId structure. MongoDB handles the conversion from string to ObjectId. 
Since we need to map the DatabaseSettings from the appsettings.json file to the Application so that it can connect with MongoDB to perform operations, we need to add a class in the application to define this mapping and register this mapping in the ASP.NET Core Service collection. In the Models folder, add a new class file named DatabaseSettings.cs. In this file, add the code as shown in Listing 3


public class DatabaseSettings
{
    public string ConnectionString { get; set; } = null!;

    public string DatabaseName { get; set; } = null!;

    public string CollectionName { get; set; } = null!;
}

Listing 3: The DatabaseSettings code
  
As shown in Listing 3, we have properties in class those map with keys for the DatabaseSettings we have added in appsettings.json.

Step 3: In the Program.cs let add the code to map the DatabaseSettings from appsettings.json with the DatabaseSettings class. The code is shown in Listing 4


builder.Services.Configure<DatabaseSettings>(
    builder.Configuration.GetSection("DatabaseSettings"));

Listing 4: Mapping the settings from appsettings.json with the DataSettings class

The Configure() method is used to register the configuration with the keys of the appsettings.json with the class passed as generic parameter of the Configure() method.

Step 4: In the project, add a new folder named Services. In this folder, add a new class file named NovelSetvice.cs. In this file we add the code for performing CRUD operations using the IMongoolletion type. The code for the class NovelService is shown in Listing 5


using Core_API_MongoDb.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;

namespace Core_API_MongoDb.Services
{
    /// <summary>
    /// This class contains code for performing CRUD 
    /// Operations on MongoDB Collection
    /// </summary>
    public class NovelService
    {
        private readonly IMongoCollection<Novel> _NovelsCollection;

        public NovelService(IOptions<DatabaseSettings> dbSettings )
        {
            // Retrieve the DbInfromation

            // Reads the server instance for running database operations. The constructor of this class is provided in the MongoDB connection string:
            var mongoClient = new MongoClient(
            dbSettings.Value.ConnectionString);
            //  Represents the Mongo database for running operations. 
            var mongoDatabase = mongoClient.GetDatabase(
                dbSettings.Value.DatabaseName);
            // the collection name.
            _NovelsCollection = mongoDatabase.GetCollection<Novel>(
                dbSettings.Value.CollectionName);
        }


        public async Task<List<Novel>> GetAsync() =>
              await _NovelsCollection.Find(_ => true).ToListAsync();

        public async Task<Novel?> GetAsync(string id) =>
            await _NovelsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(Novel novel) =>
            await _NovelsCollection.InsertOneAsync(novel);

        public async Task UpdateAsync(string id, Novel novel) =>
            await _NovelsCollection.ReplaceOneAsync(x => x.Id == id, novel);

        public async Task RemoveAsync(string id) =>
            await _NovelsCollection.DeleteOneAsync(x => x.Id == id);

    }
}

Listing 5: The NovelService class

As shown in Listing 5, the NovelService class is constructor with DataSettings class using IOptions type. The IOptions is used to retrieve configured types in the ASP.NET Core Services. We have done this in Step 3 as shown in Listing 4. The NovelService class contains code to MongoDB database and its collection in the constructor. The ConnectionString is passed to the MongoClient class. The database name is passed to the GetDatabase() method of the MongoClient instance. The Collection name is passed to the GetColletion) method of the IMogoDatabase type. The class NovelService contains  methods for performing CRUD operations using the methods of the IMongoCollection type.         

Step 5: Modify the Program.cs to register the NovelService in the Dependency Container of ASP.NET Core. The code is shown in Listing 6


builder.Services.AddSingleton<NovelService>();

Listing 6: The NovelService Registration

Step 6: Modify the Program.cs by adding API Endpoints for Novel as shown in Listing 7.


app.MapGet("/novels", async (NovelService serv) => 
{
    var novels = await serv.GetAsync();
    return Results.Ok<List<Novel>>(novels); 
});
app.MapGet("/novels/{id}", async (NovelService serv, string id) =>
{
    var novel = await serv.GetAsync(id);
    return Results.Ok<Novel>(novel);
});

app.MapPost("/novels", async (NovelService serv, Novel novel) =>
{
     await serv.CreateAsync(novel);
    return Results.Ok("Record Added Successfully");
});

app.MapPut("/novels/{id}", async (NovelService serv, string id, Novel novel) =>
{
    await serv.UpdateAsync(id,novel);
    return Results.Ok("Record Updated Successfully");
});

app.MapDelete("/novels/{id}", async (NovelService serv, string id) =>
{
    await serv.RemoveAsync(id);
    return Results.Ok("Record Deleted Successfully");
});

Listing 7: The API Endpoints for Novel

 Run the Application and test it in the swagger page. Make the POST required as shown in Figure 4.




Figure 4: The Post Request

.When the new record is posted the collection will store the data as shown in Figure 5



Figure 5: The Result in MongoDB

 Similarly, we can test all other operations.

The code for this article can be downloaded from this link.

Conclusion: While building data collection applications its better to use MongoDB database and the easy and powerful ASP.NET Core  APIs. The MongoDB.Drver is the powerful package to interact with the MongoDB database and performing Read/Write operations. 

Popular posts from this blog

Uploading Excel File to ASP.NET Core 6 application to save data from Excel to SQL Server Database

ASP.NET Core 6: Downloading Files from the Server

ASP.NET Core 6: Using Entity Framework Core with Oracle Database with Code-First Approach