Working with NoSQL Databases in ASP.NET Core: MongoDB, CosmosDB, and Document Stores
A practical guide to using MongoDB, Cosmos DB, and document databases in ASP.NET Core applications
Modern applications increasingly rely on flexible, scalable data storage. In this guide, we’ll explore how to use MongoDB and Azure Cosmos DB with ASP.NET Core, and how document databases can simplify development while supporting high-performance, cloud-native systems.
As applications grow, traditional relational databases don’t always fit every use case. They work well for structured data and strict relationships, but modern systems often deal with evolving schemas, distributed workloads, and large volumes of semi-structured data.
That’s where NoSQL databases come in.
NoSQL databases, especially document stores, allow you to store data in flexible formats like JSON. This makes it easier to evolve your application over time without constantly redesigning your schema.
In ASP.NET Core applications, NoSQL databases are often used alongside relational databases, not as replacements, but as complementary tools.
In this article, we’ll explore how document databases work, how to integrate MongoDB and Azure Cosmos DB into ASP.NET Core, and how to design systems that take advantage of their strengths.
What Are NoSQL and Document Databases?
NoSQL databases are designed to handle data that doesn’t fit neatly into tables.
Instead of rows and columns, document databases store data as documents, typically in JSON format.
A simple example:
{
“id”: “1”,
“name”: “Laptop”,
“price”: 1200,
“tags”: [”electronics”, “computers”]
}This structure is flexible. You can add fields without changing a schema.
Microsoft explains NoSQL databases as systems optimized for scalability, performance, and flexible data models:
https://learn.microsoft.com/en-us/azure/cosmos-db/overview
This flexibility is especially useful in applications where data changes frequently or varies between records.
Why Use NoSQL in ASP.NET Core Applications
NoSQL databases solve several common problems in modern applications.
They allow developers to move faster because there’s no rigid schema to manage. They scale horizontally, making them ideal for cloud environments. And they map naturally to object-oriented code since documents resemble C# objects.
For example, if you’re working with event-driven systems or messaging, storing JSON payloads directly can simplify your design. This aligns closely with patterns we discussed in our Azure Service Bus guide.
Similarly, when handling large datasets or batch workflows, document databases can reduce complexity compared to relational joins. This ties into bulk processing strategies we covered earlier.
Getting Started with MongoDB in ASP.NET Core
MongoDB is one of the most popular document databases. It stores data as BSON (binary JSON) and provides powerful querying capabilities.
Official documentation can be found here - https://www.mongodb.com/docs/
Install the MongoDB driver:
dotnet add package MongoDB.DriverConfiguring MongoDB
In appsettings.json:
{
“MongoDbSettings”: {
“ConnectionString”: “mongodb://localhost:27017”,
“DatabaseName”: “MyAppDb”
}
}Create a configuration class:
public class MongoDbSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}Register it:
builder.Services.Configure<MongoDbSettings>(
builder.Configuration.GetSection(”MongoDbSettings”));Creating a MongoDB Service
public class ProductService
{
private readonly IMongoCollection<Product> _collection;
public ProductService(IOptions<MongoDbSettings> settings)
{
var client = new MongoClient(settings.Value.ConnectionString);
var database = client.GetDatabase(settings.Value.DatabaseName);
_collection = database.GetCollection<Product>(”Products”);
}
public async Task<List<Product>> GetAsync() =>
await _collection.Find(_ => true).ToListAsync();
public async Task CreateAsync(Product product) =>
await _collection.InsertOneAsync(product);
}This structure integrates cleanly with ASP.NET Core dependency injection.
Querying Data in MongoDB
MongoDB uses expressive filters for querying.
var products = await _collection
.Find(p => p.Price > 1000)
.ToListAsync();You can also build more complex queries using builders.
Document databases shine here because queries map naturally to object structures.
Using Azure Cosmos DB with ASP.NET Core
Azure Cosmos DB is Microsoft’s globally distributed NoSQL database.
It supports multiple APIs, including a MongoDB-compatible API and a native NoSQL API.
Official documentation:
https://learn.microsoft.com/azure/cosmos-db/
Install the SDK:
dotnet add package Microsoft.Azure.CosmosConnecting to Cosmos DB
var client = new CosmosClient(connectionString);
var container = client.GetContainer(”MyDatabase”, “Products”);Inserting Data
await container.CreateItemAsync(product, new PartitionKey(product.Id));Querying Data
var query = container.GetItemQueryIterator<Product>(
“SELECT * FROM c WHERE c.price > 1000”);
var results = new List<Product>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response);
}Cosmos DB is designed for global scale and low latency, making it ideal for distributed systems.
Designing with Document Databases
When using document databases, data modeling is different.
Instead of normalizing data across tables, you often embed related data in a single document.
For example:
{
“orderId”: “123”,
“customer”: {
“name”: “John”,
“email”: “[email protected]”
},
“items”: [
{ “product”: “Laptop”, “price”: 1200 }
]
}This reduces the need for joins and improves read performance.
When to Use MongoDB vs Cosmos DB
MongoDB is a great choice when:
You want full control over your database
You’re running on your own infrastructure
You need flexible querying
Cosmos DB is ideal when:
You want a fully managed cloud service
You need global distribution
You require automatic scaling
In many ASP.NET Core applications, Cosmos DB fits naturally with Azure-based architectures.
Performance Considerations
NoSQL databases are fast, but they still require proper design.
Indexing is critical. Without indexes, queries can become slow.
MongoDB example:
await _collection.Indexes.CreateOneAsync(
new CreateIndexModel<Product>(
Builders<Product>.IndexKeys.Ascending(p => p.Price)));Cosmos DB automatically indexes data, but you can customize indexing policies for better performance.
If you’re working with high-throughput systems, performance tuning becomes essential. For deeper insights, see our performance tuning guide.
Handling Large Data Workloads
Document databases work well with large datasets, but you still need to manage memory and processing carefully.
Use pagination instead of loading all records at once.
Process data in batches when needed. This aligns with export and reporting workflows discussed here.
Real-World Example: Event Storage
Imagine an application that processes user events.
Each event is stored as a document:
{
“eventType”: “OrderPlaced”,
“timestamp”: “2026-01-01T10:00:00Z”,
“data”: {
“orderId”: “123”,
“amount”: 500
}
}This structure is flexible and works well with messaging systems.
It also integrates naturally with file-based workflows like uploads and processing.
Common Mistakes to Avoid
One common mistake is treating NoSQL databases like relational databases.
Trying to normalize everything defeats the purpose of document storage.
Another mistake is ignoring indexing. Without indexes, performance will degrade quickly.
Finally, avoid storing excessively large documents. While document databases allow flexibility, extremely large records can impact performance.
Closing Thoughts
NoSQL databases are not a replacement for relational databases, but they are an essential tool for modern applications.
MongoDB and Azure Cosmos DB provide flexible, scalable options for storing and querying data in ASP.NET Core applications.
By understanding how document databases work and designing your data models appropriately, you can build systems that are easier to maintain and scale.
As your application grows, combining NoSQL with messaging, batch processing, and export systems creates a strong foundation for handling real-world workloads.
Join The Community
Enjoyed this article? Subscribe to ASP Today for practical ASP.NET Core insights and real-world development patterns. Join our Substack Chat to connect with developers building modern applications.


