post-ad

CRUD Operations In .NET Core API Using MongoDB

In this article, we will learn about how we can perform CRUD operations in .NET Core API using MongoDB.

Prerequisites:

  • Basic knowledge of .NET Core and MongoDB.
  • Code editors like Visual Studio 2019

Create, Read, Update, and Delete operations in .NET Core API

First, we create a StudentInfo collection with given fields in MongoDB.

Create a new project

Open VS2019, we need to click on the “Create a new project” box.

Put a suitable name & select the location where you want to create this project. Again, click the “Create” button.

After that, you have to select the .net core Target Framework 3.1.

Install NuGet packages.

We need to install MongoDB.Driver.

Now open your “appsettings.json”  and copy the below code and paste it.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MongoDBSettings": {
    "ConnectionURI": "mongodb://localhost:27017",
    "DatabaseName": "Database name",
    "CollectionName": "Collection name"
  }
}

Create MongoDBSettings Class and Interface.

public class MongoDBSettings : IMongoDBSettings
{
    public string ConnectionURI { get; set; }
    public string DatabaseName { get; set; }
    public string CollectionName { get; set; }
}

public interface IMongoDBSettings
{
   public string ConnectionURI { get; set; }
   public string DatabaseName { get; set; }
   public string CollectionName { get; set; }
}

Open your Startup.cs copy the below code and paste it into the ConfigureServices method.

services.AddSingleton<IMongoDBSettings>(sp =>
sp.GetRequiredService<IOptions<MongoDBSettings>>().Value);

Now Open your controller and code and paste.

using System;
using System.Threading.Tasks;
using DotNetWithMongo.Models;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;

namespace DotNetWithMongo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private readonly IMongoCollection<StudentInfo> _students;
        public StudentController(IMongoDBSettings settings)
        {
            var client = new MongoClient(settings.ConnectionURI);
            var database = client.GetDatabase(settings.DatabaseName);

            _students = database.GetCollection<StudentInfo>(settings.CollectionName);
        }

        [HttpGet]
        [Route("GetAllStudents")]
        public IActionResult GetAllStudents()
        {
            try
            {
                var students = _students.Find(std => std.IsActive == true).ToList();
                return Ok(students);
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }

        [HttpPost]
        [Route("AddStudent")]
        public IActionResult AddStudent(StudentInfo studentInfo)
        {
            try
            {
                var options = new InsertOneOptions();
                var collection = _students.InsertOneAsync(studentInfo);
                return Ok("Student add successfully.");
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }

        [HttpPost]
        [Route("EditStudent")]
        public IActionResult EditStudent(StudentInfo studentInfo)
        {
            try
            {
                _students.ReplaceOneAsync(x => x.Id == studentInfo.Id, studentInfo);
                return Ok("Student update successfully.");
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }

        [HttpGet]
        [Route("GetByIdStudent")]
        public async Task<IActionResult> GetByIdStudent(string id)
        {
            try
            {
                var student = await _students.Find(x => x.Id == id).FirstOrDefaultAsync();
                if (student != null)
                {
                    await _students.DeleteOneAsync(x => x.Id == id);
                    return Ok(student);
                }
                else
                {
                    return Ok("Student not found!");
                }
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }

        [HttpPost]
        [Route("DeleteStudent")]
        public async Task<IActionResult> DeleteStudent(string id)
        {
            try
            {
                var student = await _students.Find(x => x.Id == id).FirstOrDefaultAsync();
                if (student != null)
                {
                    await _students.DeleteOneAsync(x => x.Id == id);
                    return Ok("Student delete successfully");
                }
                else
                {
                    return Ok("Student not found!");
                }
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }
    }
}

Conclusion

In this article, we have learned about how we can perform CRUD operations in .NET Core API using MongoDB.

Also, check CRUD Operations In .Net Core Using NHibernet

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories

page-ad