Usama Arshad

 © 2023 itsusamaarshad

.Net 6 Web Api With MongoDB

Recent Post​

What is MongoDB

MongoDB is most popular NOSQL Database. In MongoDB save data in json form. MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution are built in and easy to use.

Installing MongoDB

 

1. Download MongoDB server https://www.mongodb.com/try/download/community.

2. After download install.

 

3. Create Database and Collection in MongoDB.

Create Api Project in Visual Studio 2022

 

1. Create a web api project in visual studio 2022.

2. Add MondoDB.Driver nugget to use MongoDb.

3. Add following code in AppSetting.json.

“TodoDatabaseSettings”: 
{
“TodoCollectionName”: “TodoApp”,
“ConnectionString”: “mongodb://localhost:27017”,
“DatabaseName”: “TodoDB”
}

4. Add Models folder and add a TodoItem Model Class and paste the following below code.

using MongoDB.Bson.Serialization.Attributes; 
using MongoDB.Bson;
namespace ToDoApp.Models {
public class TodoItem {
[BsonId]
[BsonRepresentation(BsonType.Int32)]
public int Id { get; set; }
public string Title { get; set; } = null!;
public string Desc { get; set; } = string.Empty;
public bool IsDone { get; set; }
} 
}

5. Add a TodoAppDatabaseSettings Class to the Models directory with the following code.

namespace ToDoApp.Models {
public class TodoDatabaseSettings {
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string TodoCollectionName { get; set; } = null!;
}
}

6. Add the following code to Program.cs.

builder.Services.AddSingleton<TodoService>();
builder.Services.Configure<TodoDatabaseSettings>();

7. Add Services folder and   create a TodoService Class for crud operation.

using Microsoft.Extensions.Options;
using MongoDB.Driver;
using ToDoApp.Models;
namespace ToDoApp.Services
{
public class TodoService
{
private readonly IMongoCollection<TodoItem> _todoCollection;
public TodoService(
IOptions<TodoDatabaseSettings> todoAppDatabaseSettings)
{
var mongoClient = new MongoClient(
todoAppDatabaseSettings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(
todoAppDatabaseSettings.Value.DatabaseName);
_todoCollection = mongoDatabase.GetCollection<TodoItem>(
todoAppDatabaseSettings.Value.TodoCollectionName);
}
public async Task<List<TodoItem>> GetAsync() =>
await _todoCollection.Find(_ => true).ToListAsync();
public async Task<TodoItem?> GetAsync(int id) =>
await _todoCollection.Find(x => x.Id == id).FirstOrDefaultAsync();
public async Task CreateAsync(TodoItem newBook) =>
await _todoCollection.InsertOneAsync(newBook);
public async Task UpdateAsync(int id, TodoItem updatedBook) =>
await _todoCollection.ReplaceOneAsync(x => x.Id == id, updatedBook);
public async Task RemoveAsync(int id) =>
await _todoCollection.DeleteOneAsync(x => x.Id == id);
}
}

8. Add this line in program.cs file to register service for constructor injection.

builder.Services.AddSingleton<TodoService>();

9. Create a API Controller and paste below code.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ToDoApp.Models;
using ToDoApp.Services;
namespace ToDoApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
private readonly TodoService _booksService;
public TodoController(TodoService TodoService) =>
_booksService = TodoService;
[HttpGet]
public async Task<List<TodoItem>> Get() =>
await _booksService.GetAsync();
[HttpGet("{id}")]
public async Task<ActionResult<TodoItem>> Get(int id)
{
var TodoItem = await _booksService.GetAsync(id);
if (TodoItem is null)
{
return NotFound();
}
return TodoItem;
}
[HttpPost]
public async Task<IActionResult> Post(TodoItem newBook)
{
await _booksService.CreateAsync(newBook);
return CreatedAtAction(nameof(Get), new { id = newBook.Id }, newBook);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, TodoItem updatedBook)
{
var TodoItem = await _booksService.GetAsync(id);
if (TodoItem is null)
{
return NotFound();
}
updatedBook.Id = TodoItem.Id;
await _booksService.UpdateAsync(id, updatedBook);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var TodoItem = await _booksService.GetAsync(id);
if (TodoItem is null)
{
return NotFound();
}
await _booksService.RemoveAsync(id);
return NoContent();
}
}

10. Run the Project and Test the API.