Skip to content

MongoDB and Entity Framework Core – A Practical Guide

Entity Framework Core (EF Core) is a popular ORM for .NET that allows developers to interact with databases using C# objects instead of writing raw queries. Thanks to the MongoDB EF Core Provider, you can now use these familiar patterns with a NoSQL database like MongoDB.

This article explains how to connect MongoDB with EF Core, covers the key concepts, and provides a practical example you can adapt for your own projects.

Why MongoDB + EF Core?

MongoDB stores data as flexible, JSON-like documents (BSON) in collections – no rigid table schemas required. EF Core, on the other hand, gives .NET developers a consistent API for data access with LINQ queries, change tracking, and code-first workflows. Combining both means you get MongoDB’s flexibility with EF Core’s developer-friendly patterns.

Key benefits of the MongoDB EF Core Provider:

  • Code-first workflow – define models in C# and let EF Core handle the rest
  • LINQ support – query MongoDB using standard LINQ syntax
  • Change tracking – automatic detection of entity modifications
  • Embedded documents – native support for nested objects
  • Familiar API – if you know EF Core with SQL Server, the transition is smooth

Getting Started

Prerequisites

  • .NET 7.0+ SDK
  • A MongoDB Atlas account (free tier available) or a local MongoDB instance
  • Your favorite IDE (Visual Studio, VS Code, Rider)

Install the NuGet Package

dotnet add package MongoDB.EntityFrameworkCore

This also pulls in the MongoDB C# Driver and EF Core as dependencies.

Practical Example: Product Catalog

Let’s build a simple product catalog to demonstrate all CRUD operations.

1. Define the Model

using MongoDB.Bson;
using MongoDB.EntityFrameworkCore;

namespace MyApp.Models
{
    [Collection("products")]
    public class Product
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public string Category { get; set; } = string.Empty;
        public List<string> Tags { get; set; } = new();
    }
}

The [Collection("products")] attribute maps this class to the products collection in MongoDB. Notice the Tags property – MongoDB handles arrays natively, something that would require a separate table in a relational database.

2. Create the DbContext

using Microsoft.EntityFrameworkCore;
using MyApp.Models;

namespace MyApp.Data
{
    public class ProductDbContext : DbContext
    {
        public DbSet<Product> Products { get; init; }

        public ProductDbContext(DbContextOptions options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Product>();
        }
    }
}

3. Configure the Connection

using MongoDB.Driver;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;

// Create the MongoDB client
var mongoClient = new MongoClient("mongodb+srv://<user>:<password>@cluster0.xxxxx.mongodb.net");

// Configure DbContext with MongoDB
var dbContextOptions = new DbContextOptionsBuilder<ProductDbContext>()
    .UseMongoDB(mongoClient, "my_store")
    .Options;

var db = new ProductDbContext(dbContextOptions);

4. CRUD Operations

Create

var newProduct = new Product
{
    Name = "Mechanical Keyboard",
    Price = 149.99m,
    Category = "Electronics",
    Tags = new List<string> { "peripherals", "gaming", "office" }
};

db.Products.Add(newProduct);
db.SaveChanges();

Console.WriteLine($"Added product with ID: {newProduct.Id}");

Read

// All products in a category
var electronics = db.Products
    .Where(p => p.Category == "Electronics")
    .OrderBy(p => p.Price)
    .ToList();

foreach (var product in electronics)
{
    Console.WriteLine($"{product.Name} – {product.Price:C}");
}

// Single product by condition
var keyboard = db.Products
    .FirstOrDefault(p => p.Name == "Mechanical Keyboard");

Update

var productToUpdate = db.Products
    .FirstOrDefault(p => p.Name == "Mechanical Keyboard");

if (productToUpdate != null)
{
    productToUpdate.Price = 129.99m;
    productToUpdate.Tags.Add("sale");
    db.SaveChanges();
}

Delete

var productToDelete = db.Products
    .FirstOrDefault(p => p.Name == "Mechanical Keyboard");

if (productToDelete != null)
{
    db.Products.Remove(productToDelete);
    db.SaveChanges();
}

Using It in ASP.NET Core

In a real web application, you’d register the DbContext in Program.cs:

// Program.cs
var connectionString = builder.Configuration.GetConnectionString("MongoDB");
var databaseName = builder.Configuration["MongoDBSettings:DatabaseName"];

builder.Services.AddDbContext<ProductDbContext>(options =>
    options.UseMongoDB(connectionString ?? "", databaseName ?? ""));

And in appsettings.json:

{
  "ConnectionStrings": {
    "MongoDB": "mongodb+srv://<user>:<password>@cluster0.xxxxx.mongodb.net"
  },
  "MongoDBSettings": {
    "DatabaseName": "my_store"
  }
}

Then inject it into controllers or services:

public class ProductsController : Controller
{
    private readonly ProductDbContext _db;

    public ProductsController(ProductDbContext db)
    {
        _db = db;
    }

    public IActionResult Index()
    {
        var products = _db.Products.OrderBy(p => p.Name).Take(50).ToList();
        return View(products);
    }
}

Good to Know

  • No relationship support yet – the MongoDB EF Core Provider does not currently support navigation properties or relationships between entities. You can work around this by storing related IDs and querying manually.
  • Embedded documents work great – instead of joins, model nested data as properties of your entity.
  • Advanced features – for Atlas Search or Vector Search, use the MongoDB C# Driver directly alongside EF Core.
  • Change tracking – works the same as with relational databases; only modified fields are sent to MongoDB.

Summary

The MongoDB EF Core Provider lets .NET developers use the familiar EF Core API with MongoDB, bringing together the best of both worlds. You define models in C#, use LINQ for queries, and let EF Core handle the plumbing. For most CRUD use cases, the experience is nearly identical to using EF Core with SQL Server – just with the added flexibility of a document database.

Tags: