Crud operations with MongoDB in asp.net core
1. First thing we need to install the mongodb set up in local machine.
so you can download the setup from here,
https://www.mongodb.com/try/download/community,once you installed at the last you need to select the mongoDB compass option,so that it will give you the UI for mongoDB.
you can create database and collection there.
now comes to asp.net core.
dependency need to install ,means below nuget packages need to install,
Step 1 First create the web api solution in .net core with the name ASP_MongoDB,under this solution create folder for model and same for rest such as services,configurations
under configurations ,
Create class DeveloperDatabaseConfiguration and put the property as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_MongoDB.Configurations
{
public class DeveloperDatabaseConfiguration
{
public string CustomerCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
}
Step 2. Create model
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_MongoDB.Model
{
public class Customer
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
public string LastName { get; set; }
[BsonElement("PhoneNumber")]
public string Contact { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
}
}
Step 3. Create Service Folder and create class as below,
using ASP_MongoDB.Configurations;
using ASP_MongoDB.Model;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_MongoDB.Services
{
public class CustomerService
{
private readonly IMongoCollection<Customer> _customer;
private readonly DeveloperDatabaseConfiguration _settings;
public CustomerService(IOptions<DeveloperDatabaseConfiguration> settings)
{
_settings = settings.Value;
var client = new MongoClient(_settings.ConnectionString);
var database = client.GetDatabase(_settings.DatabaseName);
_customer = database.GetCollection<Customer>(_settings.CustomerCollectionName);
}
public async Task<List<Customer>> GetAllAsync()
{
return await _customer.Find(c => true).ToListAsync();
}
public async Task<Customer> GetByIdAsync(string id)
{
return await _customer.Find<Customer>(c => c.Id == id).FirstOrDefaultAsync();
}
public async Task<Customer> CreateAsync(Customer customer)
{
await _customer.InsertOneAsync(customer);
return customer;
}
public async Task UpdateAsync(string id, Customer customer)
{
await _customer.ReplaceOneAsync(c => c.Id == id, customer);
}
public async Task DeleteAsync(string id)
{
await _customer.DeleteOneAsync(c => c.Id == id);
}
}
}
Step 4. Create the appsettings as below,on mongo DB i have created the database with the name
DevelopmentDatabase and also given the name of collection Customers.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"DeveloperDatabaseConfiguration": {
"CustomerCollectionName": "Customers",
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "DevelopmentDatabase"
},
"AllowedHosts": "*"
Step 5. Now Create the Controller as below ,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ASP_MongoDB.Model;
using ASP_MongoDB.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ASP_MongoDB.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
private readonly CustomerService _customerService;
public CustomerController(CustomerService customerService)
{
_customerService = customerService;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Ok(await _customerService.GetAllAsync());
}
[HttpGet("{id:length(24)}")]
public async Task<IActionResult> Get(string id)
{
var customer = await _customerService.GetByIdAsync(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
[HttpPost]
public async Task<IActionResult> Create(Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
await _customerService.CreateAsync(customer);
return Ok(customer.Id);
}
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Update(string id, Customer customerIn)
{
var customer = await _customerService.GetByIdAsync(id);
if (customer == null)
{
return NotFound();
}
await _customerService.UpdateAsync(id, customerIn);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var customer = await _customerService.GetByIdAsync(id);
if (customer == null)
{
return NotFound();
}
await _customerService.DeleteAsync(customer.Id);
return NoContent();
}
}
}
Step 6: Now comes to startup file and put the dependency as below.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<DeveloperDatabaseConfiguration>(Configuration.GetSection("DeveloperDatabaseConfiguration"));
services.AddScoped<CustomerService>();
services.AddControllers();
}
now the service is ready to use ,so you can use
get ,post,put,delete verbs operations on postman
Get all data like below,
For posting data like below
we can also check the post data in mongo db as below.
Get Specific data as below,