Modern web applications demand scalable, high-performance databases that can efficiently manage structured and semi-structured data. MongoDB, one of the most popular NoSQL databases, pairs exceptionally well with ASP.NET Core Web API for building RESTful services.
In this tutorial, you'll learn how to create a Blogging API using ASP.NET Core and MongoDB, implement CRUD operations, configure dependency injection, and follow best practices for production-ready applications.
Prerequisites
- Before starting, make sure you have:
- Visual Studio 2022 or Visual Studio Code
- .NET 8 SDK (or later)
- MongoDB Community Server or MongoDB Atlas
- Basic knowledge of C#
- Basic understanding of REST APIs
Why Choose MongoDB?
MongoDB stores data as BSON documents instead of tables.
Benefits include:
- Flexible schema
- High performance
- Horizontal scalability
- Easy JSON integration
- Excellent support for cloud applications
Unlike SQL databases, MongoDB doesn't require predefined tables or complex JOIN operations.
Step 1: Create ASP.NET Core Web API
Create a new project.
dotnet new webapi -n BloggingApi
Navigate into the project.
cd BloggingApi
Step 2: Install MongoDB Driver
Install the official MongoDB package.
dotnet add package MongoDB.Driver
This package allows ASP.NET Core applications to communicate with MongoDB.
Step 3: Configure appsettings.json
{
"MongoDbSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "BlogDb",
"PostsCollection": "Posts"
}
}
Step 4: Create the Blog Model
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class BlogPost
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public DateTime CreatedDate { get; set; }
}
Step 5: Create MongoDB Settings Class
public class MongoDbSettings
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string PostsCollection { get; set; } = null!;
}
Step 6: Register MongoDB Services
Program.cs
builder.Services.Configure<MongoDbSettings>(
builder.Configuration.GetSection("MongoDbSettings"));
builder.Services.AddSingleton<BlogService>();
Step 7: Create Blog Service
using Microsoft.Extensions.Options;
using MongoDB.Driver;
public class BlogService
{
private readonly IMongoCollection<BlogPost> _posts;
public BlogService(IOptions<MongoDbSettings> settings)
{
var mongoClient = new MongoClient(settings.Value.ConnectionString);
var database = mongoClient.GetDatabase(settings.Value.DatabaseName);
_posts = database.GetCollection<BlogPost>(
settings.Value.PostsCollection);
}
public async Task<List<BlogPost>> GetAsync() =>
await _posts.Find(_ => true).ToListAsync();
public async Task<BlogPost?> GetAsync(string id) =>
await _posts.Find(x => x.Id == id).FirstOrDefaultAsync();
public async Task CreateAsync(BlogPost post) =>
await _posts.InsertOneAsync(post);
public async Task UpdateAsync(string id, BlogPost post) =>
await _posts.ReplaceOneAsync(x => x.Id == id, post);
public async Task DeleteAsync(string id) =>
await _posts.DeleteOneAsync(x => x.Id == id);
}
Step 8: Create Blog Controller
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class BlogsController : ControllerBase
{
private readonly BlogService _service;
public BlogsController(BlogService service)
{
_service = service;
}
[HttpGet]
public async Task<IEnumerable<BlogPost>> Get()
=> await _service.GetAsync();
[HttpGet("{id}")]
public async Task<ActionResult<BlogPost>> Get(string id)
{
var post = await _service.GetAsync(id);
if (post == null)
return NotFound();
return post;
}
[HttpPost]
public async Task<IActionResult> Create(BlogPost post)
{
post.CreatedDate = DateTime.UtcNow;
await _service.CreateAsync(post);
return CreatedAtAction(nameof(Get), new { id = post.Id }, post);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, BlogPost post)
{
await _service.UpdateAsync(id, post);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
await _service.DeleteAsync(id);
return NoContent();
}
}
Testing the API
GET
GET /api/blogs
Returns all blog posts.
GET by ID
GET /api/blogs/{id}
Returns a single post.
POST
POST /api/blogs
{
"title":"MongoDB Tutorial",
"content":"Learning MongoDB with ASP.NET Core",
"author":"John"
}
PUT
PUT /api/blogs/{id}
Updates an existing blog.
DELETE
DELETE /api/blogs/{id}
Deletes the blog.
Folder Structure
BloggingApi
│
├── Controllers
│ BlogsController.cs
│
├── Models
│ BlogPost.cs
│ MongoDbSettings.cs
│
├── Services
│ BlogService.cs
│
├── Program.cs
│
└── appsettings.json
Best Practices
- Use Dependency Injection
- Register services using ASP.NET Core's built-in dependency injection container.
- Validate Models
- Use Data Annotations or FluentValidation to validate incoming requests.
- Handle Exceptions
- Implement global exception handling middleware to return consistent error responses.
- Use Asynchronous Methods
- MongoDB provides asynchronous APIs that improve scalability and responsiveness.
- Secure Connection Strings
- Store MongoDB connection strings securely using environment variables, Secret Manager, or a secure vault instead of hardcoding them.
- Create Indexes
- Create indexes on frequently queried fields to improve query performance.
Example:
db.Posts.createIndex({ Title: 1 })
- Use MongoDB Atlas
- For production applications, MongoDB Atlas offers managed hosting, automated backups, monitoring, and horizontal scaling.
Advantages of MongoDB with ASP.NET Core
- Fast API development
- Flexible document schema
- High-performance CRUD operations
- Easy JSON serialization
- Excellent cloud support
- Horizontal scalability
- Official .NET driver support
- Seamless integration with dependency injection
Common Interview Questions
Why use MongoDB instead of SQL Server?
MongoDB offers flexible schemas, better horizontal scalability, and is well suited for document-based applications, whereas SQL Server excels at relational data and complex transactions.
Is MongoDB ACID compliant?
Yes. MongoDB supports ACID transactions, including multi-document transactions, for scenarios that require strong consistency.
Can MongoDB handle millions of records?
Yes. MongoDB is designed to scale horizontally through sharding and can efficiently manage very large datasets.
Is MongoDB suitable for enterprise applications?
Absolutely. Many enterprise systems use MongoDB for content management, analytics, IoT, e-commerce, and microservices architectures.
Conclusion
Combining MongoDB with ASP.NET Core Web API enables developers to build fast, scalable, and flexible REST APIs with minimal configuration. Using the official MongoDB .NET Driver, dependency injection, and asynchronous programming patterns, you can quickly create production-ready CRUD services. As your application grows, features like indexing, validation, authentication, logging, and managed hosting with MongoDB Atlas can further enhance performance, reliability, and maintainability.