MongoDB
suggest changeMongoDB is a document database. Instead of rows in tables it stores documents, JSON-like objects with nested objects and arrays, in collections. Documents in one collection don't need the same fields, so you can store an order together with its lines in a single document instead of joining several tables.
On the wire and on disk documents are BSON, a binary JSON with extra types such as ObjectId, dates, 64-bit integers and Decimal128.
The official .NET driver is the MongoDB.Driver package. It maps C# classes and records to documents, translates lambdas and LINQ into MongoDB queries, and has an async API throughout.
Examples use C# 14 / .NET 10 as file-based programs (dotnet run app.cs) and the 3.x driver. In a project, add the package with dotnet add package MongoDB.Driver.
You need a server on localhost:27017. Transactions and change streams only work on a replica set, so start a single-node replica set:
docker run -d --name mongo -p 27017:27017 mongo:8 --replSet rs0 --bind_ip_all
docker exec mongo mongosh --quiet --eval "rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'localhost:27017'}]})"
A free MongoDB Atlas cluster works too. Use its mongodb+srv://... connection string instead of mongodb://localhost:27017.
Connecting
MongoClient owns the connection pool and keeps track of the servers. Create it once and share it, for example as a singleton. It's thread-safe, and so are the IMongoDatabase and IMongoCollection<T> objects you get from it.
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Driver;
// one MongoClient per application: it's thread-safe and owns the connection pool
var client = new MongoClient("mongodb://localhost:27017");
// databases and collections are created lazily, on the first write
IMongoDatabase db = client.GetDatabase("shop");
BsonDocument ping = await db.RunCommandAsync<BsonDocument>(new BsonDocument("ping", 1));
Console.WriteLine($"ping ok: {ping["ok"]}");
List<string> names = await (await client.ListDatabaseNamesAsync()).ToListAsync();
Console.WriteLine($"databases: {string.Join(", ", names)}");
ping ok: 1
databases: admin, config, local
The constructor doesn't connect. The connection opens in the background, and the first operation waits for a usable server. Use MongoClientSettings to change pool sizes and timeouts:
#:package MongoDB.Driver@3.12.0
using MongoDB.Driver;
var settings = MongoClientSettings.FromConnectionString("mongodb://localhost:27017");
settings.ApplicationName = "shop-api"; // shows up in server logs
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); // default is 30s
settings.MaxConnectionPoolSize = 50; // default is 100
var client = new MongoClient(settings);
Console.WriteLine(client.Settings.ServerSelectionTimeout);
// an unreachable server fails at the first operation, not in the constructor
var bad = new MongoClient("mongodb://localhost:1/?serverSelectionTimeoutMS=1000");
try
{
await bad.ListDatabaseNamesAsync();
}
catch (TimeoutException e)
{
Console.WriteLine($"{e.GetType().Name}: {e.Message.Split(" using ")[0]}");
}
00:00:05
TimeoutException: A timeout occurred after 1009ms selecting a server
Most settings can also go in the connection string, for example mongodb://user:pass@host1,host2/?replicaSet=rs0&maxPoolSize=50&appName=shop-api. Keep credentials out of source code. See Connection Strings.
Mapping classes to documents
GetCollection<T> gives you a typed collection. The driver serializes T by reflection: every public property becomes a field, and a property named Id becomes the _id primary key. An ObjectId id is generated by the driver when you insert a document without one.
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("shop");
await db.DropCollectionAsync("products"); // start fresh for the demo
IMongoCollection<Product> products = db.GetCollection<Product>("products");
var mouse = new Product { Name = "Mouse", Price = 24.99m, Tags = ["usb", "wireless"], Stock = 40 };
await products.InsertOneAsync(mouse);
Console.WriteLine($"generated id: {mouse.Id != ObjectId.Empty}, created {mouse.Id.CreationTime:yyyy}");
await products.InsertManyAsync(
[
new Product { Name = "Keyboard", Price = 49.50m, Tags = ["usb"], Stock = 12 },
new Product { Name = "Monitor", Price = 199m, Tags = ["hdmi", "4k"], Stock = 3 },
new Product { Name = "Cable", Price = 4.25m, Tags = ["hdmi"], Stock = 0 },
]);
// see exactly what was stored, through an untyped view of the same collection
var raw = db.GetCollection<BsonDocument>("products");
BsonDocument doc = await raw.Find(new BsonDocument("name", "Mouse")).FirstAsync();
doc.Remove("_id");
Console.WriteLine(doc);
Product? found = await products.Find(p => p.Id == mouse.Id).FirstOrDefaultAsync();
Console.WriteLine($"{found?.Name} costs {found?.Price}");
public class Product
{
public ObjectId Id { get; set; } // mapped to _id, generated on insert
[BsonElement("name")]
public string Name { get; set; } = "";
[BsonElement("price")]
public decimal Price { get; set; }
[BsonElement("tags")]
public List<string> Tags { get; set; } = [];
[BsonElement("stock")]
public int Stock { get; set; }
}
generated id: True, created 2026
{ "name" : "Mouse", "price" : { "$numberDecimal" : "24.99" }, "tags" : ["usb", "wireless"], "stock" : 40 }
Mouse costs 24.99
ObjectId is a 12-byte id that starts with a timestamp, so ids sort roughly by insertion time and CreationTime tells you when the document was created.
Useful attributes from MongoDB.Bson.Serialization.Attributes:
| Attribute | Effect |
|---|---|
[BsonId] |
use this property as _id (needed when it isn't called Id) |
[BsonElement("n")] |
field name in the document |
[BsonIgnore] |
don't store the property |
[BsonIgnoreIfNull] / [BsonIgnoreIfDefault] |
leave the field out instead of storing null / the default |
[BsonRepresentation(BsonType.ObjectId)] |
e.g. a string property stored as ObjectId |
[BsonIgnoreExtraElements] |
don't throw when the document has fields the class lacks |
[BsonDateTimeOptions(Kind = DateTimeKind.Local)] |
return dates as local time instead of UTC |
Conventions instead of attributes
Attributes on every property get tedious. A convention pack applies rules to all mapped types. Register it once at startup, before the driver touches any of those types:
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
// register once, at startup, before the first use of any mapped type
var pack = new ConventionPack
{
new CamelCaseElementNameConvention(), // Name -> "name"
new IgnoreExtraElementsConvention(true), // tolerate fields the class doesn't have
new EnumRepresentationConvention(BsonType.String),
};
ConventionRegistry.Register("app", pack, type => true);
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
var db = new MongoClient("mongodb://localhost:27017").GetDatabase("shop");
await db.DropCollectionAsync("orders");
var orders = db.GetCollection<Order>("orders");
var order = new Order(Guid.NewGuid(), "alice", 74.49m, Status.Paid, DateTime.UtcNow,
[new Line("Mouse", 1, 24.99m), new Line("Keyboard", 1, 49.50m)]);
await orders.InsertOneAsync(order);
var raw = await db.GetCollection<BsonDocument>("orders").Find(FilterDefinition<BsonDocument>.Empty).FirstAsync();
raw["_id"] = "...";
raw["createdAt"] = "...";
Console.WriteLine(raw);
Order back = await orders.Find(o => o.Customer == "alice").SingleAsync();
Console.WriteLine($"{back.Customer} {back.Status} {back.Lines.Count} lines, kind={back.CreatedAt.Kind}");
public enum Status { New, Paid, Shipped }
public record Line(string Product, int Quantity, decimal Price);
// records work: the driver maps the constructor parameters to the properties
public record Order(Guid Id, string Customer, decimal Total, Status Status,
DateTime CreatedAt, List<Line> Lines);
{ "_id" : "...", "customer" : "alice", "total" : { "$numberDecimal" : "74.49" }, "status" : "Paid", "createdAt" : "...", "lines" : [{ "product" : "Mouse", "quantity" : 1, "price" : { "$numberDecimal" : "24.99" } }, { "product" : "Keyboard", "quantity" : 1, "price" : { "$numberDecimal" : "49.50" } }] }
alice Paid 2 lines, kind=Utc
Things to know about type mapping:
- Guid: since driver 3.0 there's no default representation, and storing a
GuidthrowsGuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecifieduntil you registerGuidSerializer(GuidRepresentation.Standard)as above, or put[BsonGuidRepresentation(GuidRepresentation.Standard)]on the property. - decimal is stored as
Decimal128, an exact decimal that the server can compare and sum. - DateTime is stored in UTC with millisecond precision. Local times are converted to UTC on the way in, and values come back with
Kind == Utc. - Enums are stored as integers unless you use
EnumRepresentationConventionor[BsonRepresentation(BsonType.String)]. Strings are easier to read and survive reordering the enum members. - Without
IgnoreExtraElements, reading a document that has a field your class doesn't have throwsFormatException. That happens as soon as a newer version of your app adds a field.
Querying
The examples in the following sections, up to and including Bulk writes, use the products collection and Product class from the start of the previous section, and each starts with the same four products (Mouse, Keyboard, Monitor, Cable). They also need using MongoDB.Driver.Linq;.
Find takes a filter, either a lambda or one built with Builders<T>.Filter. Either way it's translated to a MongoDB query and runs on the server.
// a lambda is translated to a MongoDB query, it doesn't run on the client
List<Product> cheap = await products.Find(p => p.Price < 30m)
.SortBy(p => p.Price)
.ToListAsync();
Console.WriteLine("cheap: " + string.Join(", ", cheap.Select(p => p.Name)));
// Builders create the same filters and can be combined with & | !
var f = Builders<Product>.Filter;
var filter = f.AnyEq(p => p.Tags, "hdmi") & f.Gt(p => p.Stock, 0);
Console.WriteLine("hdmi in stock: " + (await products.Find(filter).FirstAsync()).Name);
var named = f.In(p => p.Name, ["Mouse", "Cable"]) | f.Regex(p => p.Name, new BsonRegularExpression("^key", "i"));
Console.WriteLine("named: " + string.Join(", ", (await products.Find(named).ToListAsync()).Select(p => p.Name)));
// sort, paging and projection to an anonymous type: only name and price are sent back
var page = await products.Find(FilterDefinition<Product>.Empty)
.SortByDescending(p => p.Price)
.Skip(1).Limit(2)
.Project(p => new { p.Name, p.Price })
.ToListAsync();
foreach (var p in page) Console.WriteLine($" {p.Name,-9} {p.Price,7}");
long inStock = await products.CountDocumentsAsync(p => p.Stock > 0);
Console.WriteLine($"in stock: {inStock}, all: {await products.EstimatedDocumentCountAsync()}");
// large results: iterate the cursor, documents arrive in batches
await foreach (Product p in products.Find(p => p.Tags.Contains("usb")).ToAsyncEnumerable())
Console.WriteLine($"usb: {p.Name}");
cheap: Cable, Mouse
hdmi in stock: Monitor
named: Mouse, Keyboard, Cable
Keyboard 49.50
Mouse 24.99
in stock: 3, all: 4
usb: Mouse
usb: Keyboard
FirstAsync throws if nothing matches, FirstOrDefaultAsync returns null, and SingleAsync also throws if more than one document matches. CountDocumentsAsync runs a query, while EstimatedDocumentCountAsync reads collection metadata and is instant on huge collections.
LINQ
AsQueryable() supports the usual LINQ operators. The whole query is translated into an aggregation pipeline, so Where, GroupBy, Sum and friends run on the server:
// AsQueryable() turns LINQ into an aggregation pipeline that runs on the server
IQueryable<Product> query = products.AsQueryable()
.Where(p => p.Stock > 0 && p.Price < 100m)
.OrderBy(p => p.Name);
Console.WriteLine(query); // shows the generated pipeline
foreach (Product p in await query.ToListAsync())
Console.WriteLine($"{p.Name}: {p.Stock}");
var byTag = await products.AsQueryable()
.SelectMany(p => p.Tags, (p, tag) => new { Tag = tag, p.Stock })
.GroupBy(x => x.Tag)
.Select(g => new { Tag = g.Key, Count = g.Count(), Stock = g.Sum(x => x.Stock) })
.OrderBy(x => x.Tag)
.ToListAsync();
foreach (var t in byTag) Console.WriteLine($"{t.Tag,-9} products={t.Count} stock={t.Stock}");
// Find() can show its query too
Console.WriteLine(products.Find(p => p.Name == "Mouse").Limit(1));
shop.products.Aggregate([{ "$match" : { "stock" : { "$gt" : 0 }, "price" : { "$lt" : { "$numberDecimal" : "100" } } } }, { "$sort" : { "name" : 1 } }])
Keyboard: 12
Mouse: 40
4k products=1 stock=3
hdmi products=2 stock=3
usb products=2 stock=52
wireless products=1 stock=40
Use the async versions (ToListAsync, FirstOrDefaultAsync, CountAsync) from MongoDB.Driver.Linq. A method the driver can't translate, such as one of your own helpers inside Where, throws ExpressionNotSupportedException instead of silently running on the client. Printing a query is the quickest way to check what is sent to the server.
Updating
Update operators ($set, $inc, $push, ...) change documents in place on the server. They're atomic per document, so two clients decrementing the same stock counter never lose an update. Build them with Builders<T>.Update and chain several operators in one update:
var u = Builders<Product>.Update;
// update operators change fields in place on the server; no read-modify-write race
UpdateResult r = await products.UpdateOneAsync(
p => p.Name == "Mouse",
u.Inc(p => p.Stock, -1).AddToSet(p => p.Tags, "sale").Set(p => p.Price, 19.99m));
Console.WriteLine($"matched={r.MatchedCount} modified={r.ModifiedCount}");
// update many documents at once
r = await products.UpdateManyAsync(p => p.Tags.Contains("hdmi"), u.Mul(p => p.Price, 0.9m));
Console.WriteLine($"discounted {r.ModifiedCount} hdmi products");
// upsert: update if it exists, insert otherwise
r = await products.UpdateOneAsync(
p => p.Name == "Webcam",
u.Set(p => p.Price, 59m).SetOnInsert(p => p.Stock, 5),
new UpdateOptions { IsUpsert = true });
Console.WriteLine($"upserted id: {r.UpsertedId?.BsonType}");
// FindOneAndUpdate is atomic and returns the document, here the version after the change
Product? reserved = await products.FindOneAndUpdateAsync(
p => p.Name == "Monitor" && p.Stock > 0, // only if something is left
u.Inc(p => p.Stock, -1),
new FindOneAndUpdateOptions<Product> { ReturnDocument = ReturnDocument.After });
Console.WriteLine($"reserved monitor, {reserved?.Stock} left, price {reserved?.Price}");
// ReplaceOne swaps the whole document (except _id)
Product kb = await products.Find(p => p.Name == "Keyboard").FirstAsync();
kb.Price = 45m;
kb.Tags.Add("mechanical");
await products.ReplaceOneAsync(p => p.Id == kb.Id, kb);
foreach (var p in await products.Find(_ => true).SortBy(p => p.Name).ToListAsync())
Console.WriteLine($" {p.Name,-9} {p.Price,7} stock={p.Stock,-3} [{string.Join(",", p.Tags)}]");
matched=1 modified=1
discounted 2 hdmi products
upserted id: ObjectId
reserved monitor, 2 left, price 179.1
Cable 3.825 stock=0 [hdmi]
Keyboard 45 stock=12 [usb,mechanical]
Monitor 179.1 stock=2 [hdmi,4k]
Mouse 19.99 stock=39 [usb,wireless,sale]
Webcam 59 stock=5 []
Other update operators include Unset, Push, Pull, PopFirst, Min, Max, Rename and CurrentDate. Prefer them to ReplaceOne: a read-modify-replace sequence overwrites changes another client made in between, unless you add a version field to the filter (optimistic concurrency).
Deleting
DeleteResult d = await products.DeleteOneAsync(p => p.Name == "Cable");
Console.WriteLine($"deleted {d.DeletedCount}");
d = await products.DeleteManyAsync(p => p.Stock < 20);
Console.WriteLine($"deleted {d.DeletedCount}");
Product? gone = await products.FindOneAndDeleteAsync(p => p.Name == "Mouse");
Console.WriteLine($"removed {gone?.Name}, {await products.CountDocumentsAsync(_ => true)} left");
deleted 1
deleted 2
removed Mouse, 0 left
DeleteManyAsync(_ => true) empties a collection, while db.DropCollectionAsync("products") removes the collection together with its indexes, and is much faster.
Indexes
Without an index every query scans the whole collection. Create indexes for the fields you filter and sort on. Creating an index that already exists with the same options does nothing, so it's common to run this at application startup:
var keys = Builders<Product>.IndexKeys;
// unique index on name, compound index for "tag + price" queries
await products.Indexes.CreateManyAsync(
[
new CreateIndexModel<Product>(keys.Ascending(p => p.Name),
new CreateIndexOptions { Unique = true, Name = "name_unique" }),
new CreateIndexModel<Product>(keys.Ascending(p => p.Tags).Descending(p => p.Price)),
]);
foreach (BsonDocument ix in await (await products.Indexes.ListAsync()).ToListAsync())
Console.WriteLine($"{ix["name"]}: {ix["key"]}");
try
{
await products.InsertOneAsync(new Product { Name = "Mouse", Price = 9m });
}
catch (MongoWriteException e) when (e.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
Console.WriteLine($"duplicate: code {e.WriteError.Code}");
}
_id_: { "_id" : 1 }
name_unique: { "name" : 1 }
tags_1_price_-1: { "tags" : 1, "price" : -1 }
duplicate: code 11000
An index on an array field (tags) is a multikey index with one entry per element, so AnyEq(p => p.Tags, "hdmi") can use it. Other index kinds are text (keys.Text), geospatial (keys.Geo2DSphere), hashed, and TTL indexes that expire documents (there's an example in the BsonDocument section below).
Aggregation
The aggregation pipeline is MongoDB's equivalent of GROUP BY, joins ($lookup) and reporting queries. Aggregate() starts a typed fluent pipeline:
// typed fluent pipeline: $match -> $unwind -> $group -> $sort
var stats = await products.Aggregate()
.Match(p => p.Stock > 0)
.Unwind<Product, UnwoundProduct>(p => p.Tags)
.Group(x => x.Tags, g => new
{
Tag = g.Key,
Count = g.Count(),
AvgPrice = g.Average(x => x.Price),
Value = g.Sum(x => x.Price * x.Stock),
})
.SortByDescending(x => x.Value)
.ToListAsync();
foreach (var s in stats)
Console.WriteLine($"{s.Tag,-9} n={s.Count} avg={s.AvgPrice:F2} value={s.Value:F2}");
// the same pipeline can be written as raw stages, e.g. copied from mongosh
BsonDocument[] pipeline =
[
new("$group", new BsonDocument { { "_id", BsonNull.Value }, { "units", new BsonDocument("$sum", "$stock") } }),
];
BsonDocument total = await products.Aggregate<BsonDocument>(pipeline).FirstAsync();
Console.WriteLine($"units in stock: {total["units"]}");
class UnwoundProduct
{
public ObjectId Id { get; set; }
[BsonElement("name")] public string Name { get; set; } = "";
[BsonElement("price")] public decimal Price { get; set; }
[BsonElement("tags")] public string Tags { get; set; } = ""; // one tag after $unwind
[BsonElement("stock")] public int Stock { get; set; }
}
usb n=2 avg=37.25 value=1593.60
wireless n=1 avg=24.99 value=999.60
4k n=1 avg=199.00 value=597.00
hdmi n=1 avg=199.00 value=597.00
units in stock: 55
$unwind turns one product with two tags into two documents with one tag each, which is why it needs an output type where Tags is a single string. For quick reports the LINQ version shown earlier is often shorter.
Bulk writes
Sending thousands of separate inserts or updates means thousands of round trips. BulkWriteAsync sends a mixed list of operations in batches:
var models = new List<WriteModel<Product>>
{
new InsertOneModel<Product>(new Product { Name = "Headset", Price = 79m, Stock = 7 }),
new UpdateOneModel<Product>(
Builders<Product>.Filter.Eq(p => p.Name, "Cable"),
Builders<Product>.Update.Set(p => p.Stock, 100)),
new DeleteOneModel<Product>(Builders<Product>.Filter.Eq(p => p.Name, "Monitor")),
new ReplaceOneModel<Product>(
Builders<Product>.Filter.Eq(p => p.Name, "Speaker"),
new Product { Name = "Speaker", Price = 35m, Stock = 2 }) { IsUpsert = true },
};
// one round trip; IsOrdered = false lets the server continue after a failed operation
BulkWriteResult<Product> res = await products.BulkWriteAsync(models,
new BulkWriteOptions { IsOrdered = false });
Console.WriteLine($"inserted={res.InsertedCount} modified={res.ModifiedCount} " +
$"deleted={res.DeletedCount} upserted={res.Upserts.Count}");
inserted=1 modified=1 deleted=1 upserted=1
With the default IsOrdered = true the server stops at the first error. With false it runs the remaining operations and reports all failures together in a MongoBulkWriteException. InsertManyAsync is a bulk write too.
BsonDocument and schemaless data
When documents don't have a fixed shape, or you're writing tools that work with any collection, use BsonDocument. It's a dictionary of BsonValues with conversions such as AsString, AsInt32, AsBsonArray and ToUniversalTime():
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Driver;
var db = new MongoClient("mongodb://localhost:27017").GetDatabase("shop");
await db.DropCollectionAsync("events");
IMongoCollection<BsonDocument> events = db.GetCollection<BsonDocument>("events");
// BsonDocument is a dictionary-like DOM for schemaless data
var doc = new BsonDocument
{
{ "type", "login" },
{ "user", "alice" },
{ "at", DateTime.UtcNow },
{ "meta", new BsonDocument { { "ip", "10.0.0.7" }, { "agent", "curl/8.10" } } },
{ "scores", new BsonArray { 3, 5, 8 } },
};
await events.InsertOneAsync(doc);
Console.WriteLine($"_id was added: {doc["_id"].BsonType}");
// TTL index: the server deletes documents about an hour after their "at" time
await events.Indexes.CreateOneAsync(new CreateIndexModel<BsonDocument>(
Builders<BsonDocument>.IndexKeys.Ascending("at"),
new CreateIndexOptions { ExpireAfter = TimeSpan.FromHours(1) }));
// filters by field name; dotted paths reach into nested documents
var f = Builders<BsonDocument>.Filter;
BsonDocument e = await events.Find(f.Eq("meta.ip", "10.0.0.7") & f.Gt("scores", 7)).FirstAsync();
Console.WriteLine(e["user"].AsString);
Console.WriteLine(e["meta"]["agent"]);
Console.WriteLine(e["scores"].AsBsonArray.Sum(v => v.AsInt32));
Console.WriteLine(e.GetValue("missing", "n/a"));
Console.WriteLine(e["at"].ToUniversalTime().Kind);
// JSON text in and out
var parsed = BsonDocument.Parse("""{ "type": "logout", "user": "bob", "n": NumberLong(2) }""");
await events.InsertOneAsync(parsed);
parsed.Remove("_id");
Console.WriteLine(parsed.ToJson());
_id was added: ObjectId
alice
curl/8.10
16
n/a
Utc
{ "type" : "logout", "user" : "bob", "n" : 2 }
AsInt32 and similar throw InvalidCastException when the value has another BSON type. Use IsInt32, or ToInt32(), which converts. A typed collection and a BsonDocument collection can point to the same MongoDB collection, which is handy for migrations and debugging.
Transactions
A single-document update is always atomic. When you must change several documents all-or-nothing, use a multi-document transaction. It needs a replica set or sharded cluster, not a standalone server. WithTransactionAsync starts the transaction, commits it, aborts it when your callback throws, and retries on transient errors such as write conflicts:
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Driver;
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("bank");
await db.DropCollectionAsync("accounts");
var accounts = db.GetCollection<Account>("accounts");
await accounts.InsertManyAsync([new Account("alice", 100m), new Account("bob", 20m)]);
async Task Transfer(string from, string to, decimal amount)
{
using IClientSessionHandle session = await client.StartSessionAsync();
// commits at the end, aborts on exception, and retries transient errors
await session.WithTransactionAsync(async (s, ct) =>
{
var u = Builders<Account>.Update;
await accounts.UpdateOneAsync(s, a => a.Id == to,
u.Inc(a => a.Balance, amount), cancellationToken: ct);
var debited = await accounts.UpdateOneAsync(s,
a => a.Id == from && a.Balance >= amount,
u.Inc(a => a.Balance, -amount), cancellationToken: ct);
if (debited.ModifiedCount == 0) // throwing undoes the credit above
throw new InvalidOperationException($"{from} has insufficient funds");
return true;
});
}
await Transfer("alice", "bob", 30m);
try
{
await Transfer("bob", "alice", 500m);
}
catch (InvalidOperationException e)
{
Console.WriteLine($"rolled back: {e.Message}");
}
foreach (var a in await accounts.Find(_ => true).SortBy(a => a.Id).ToListAsync())
Console.WriteLine($"{a.Id}: {a.Balance}");
record Account(string Id, decimal Balance);
rolled back: bob has insufficient funds
alice: 70
bob: 50
Pass the session as the first argument to every operation that should be part of the transaction. An operation without it runs outside the transaction and is committed immediately. Because the callback may run more than once, keep side effects like sending email out of it. Transactions are slower than single-document writes, so the usual MongoDB design is to keep data that changes together in one document and use transactions only where that isn't possible.
Change streams
A change stream delivers inserts, updates and deletes as they happen, which is useful for cache invalidation, notifications or syncing data elsewhere. Like transactions, it needs a replica set.
#:package MongoDB.Driver@3.12.0
using MongoDB.Bson;
using MongoDB.Driver;
var db = new MongoClient("mongodb://localhost:27017").GetDatabase("shop");
await db.DropCollectionAsync("orders");
var orders = db.GetCollection<BsonDocument>("orders");
await db.CreateCollectionAsync("orders");
// only inserts and updates; the filter runs on the server
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>()
.Match(c => c.OperationType == ChangeStreamOperationType.Insert ||
c.OperationType == ChangeStreamOperationType.Update);
var options = new ChangeStreamOptions { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
using IChangeStreamCursor<ChangeStreamDocument<BsonDocument>> cursor =
await orders.WatchAsync(pipeline, options);
// make some changes from another task
_ = Task.Run(async () =>
{
await orders.InsertOneAsync(new BsonDocument { { "_id", 1 }, { "status", "new" } });
await orders.UpdateOneAsync(new BsonDocument("_id", 1),
new BsonDocument("$set", new BsonDocument("status", "paid")));
});
int seen = 0;
while (seen < 2 && await cursor.MoveNextAsync())
{
foreach (var change in cursor.Current)
{
Console.WriteLine($"{change.OperationType}: {change.FullDocument}");
seen++;
}
}
// cursor.GetResumeToken() can be saved to continue after a restart (ResumeAfter option)
Insert: { "_id" : 1, "status" : "new" }
Update: { "_id" : 1, "status" : "paid" }
You can also watch a whole database (db.WatchAsync) or the whole deployment (client.WatchAsync).
Using MongoDB in ASP.NET Core
Register IMongoClient as a singleton. Collections are thread-safe too, so they can be singletons as well:
#:sdk Microsoft.NET.Sdk.Web
#:package MongoDB.Driver@3.12.0
#:property PublishAot=false
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IMongoClient>(_ =>
new MongoClient(builder.Configuration.GetConnectionString("Mongo") ?? "mongodb://localhost:27017"));
builder.Services.AddSingleton(sp =>
sp.GetRequiredService<IMongoClient>().GetDatabase("shop").GetCollection<Note>("notes"));
var app = builder.Build();
app.MapPost("/notes", async (IMongoCollection<Note> notes, Note note) =>
{
await notes.InsertOneAsync(note);
return Results.Created($"/notes/{note.Id}", note);
});
app.MapGet("/notes/{id}", async (IMongoCollection<Note> notes, string id) =>
ObjectId.TryParse(id, out _) && await notes.Find(n => n.Id == id).FirstOrDefaultAsync() is { } note
? Results.Ok(note)
: Results.NotFound());
app.Run();
public class Note
{
// a string in C# and JSON, stored as an ObjectId in MongoDB
[BsonId, BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string Text { get; set; } = "";
}
$ curl -X POST -H "Content-Type: application/json" -d '{"text":"buy milk"}' http://localhost:5000/notes
{"id":"6ad3ce296269cbb0c688a740","text":"buy milk"}
$ curl http://localhost:5000/notes/6ad3ce296269cbb0c688a740
{"id":"6ad3ce296269cbb0c688a740","text":"buy milk"}
System.Text.Json doesn't know ObjectId and would serialize it as an object with timestamp and creationTime fields. A string id stored as ObjectId keeps the JSON clean. #:property PublishAot=false is needed because file-based web apps default to Native AOT, where reflection-based JSON serialization of Note is disabled. See dependency injection for more about service lifetimes.
If you prefer Entity Framework Core, the MongoDB.EntityFrameworkCore provider maps a DbContext to MongoDB. It supports a subset of EF features, and the driver API shown here is still needed for aggregations, bulk writes and change streams.
Tips
- Create one
MongoClientper application (per connection string) and reuse it. Creating clients per request exhausts connections. - Use the async API in servers. Every method has an
...Asyncversion that takes aCancellationToken. - Register conventions and serializers once, before any other driver use. Mappings are cached the first time a type is used.
- Turn on
IgnoreExtraElementsfor classes read by more than one version of your application, so adding a field doesn't break older code. - Design documents around how you read them. Embed data that's read together (order lines inside the order). Reference data that's shared or grows without bound (customers, comments). A document can't be larger than 16 MB.
- Index every query that runs often, and check that queries use an index with
explainin mongosh or the Atlas performance advisor. - Prefer update operators and
FindOneAndUpdateto read-modify-write. They're atomic and avoid lost updates. - For other databases from C#, see MySQL, Using SQLite and Redis.