The Same Work from C#

The official C# driver, MongoDB.Driver from NuGet, does in a .NET 10 program what you've done in mongosh and Node, with a Pet class mapped to documents, filters from a builder or LINQ, and awaited calls such as InsertOneAsync.

Journeyman · MongoDB · C# · Updated

By

After this lesson you can

  • Read a C# class mapped to MongoDB documents, from the Id property that becomes _id to the field names BsonElement gives
  • Match a C# driver call to its mongosh twin, from Find with a filter builder or LINQ to InsertOneAsync

Key takeaways

  • The official C# driver is the NuGet package MongoDB.Driver, and a .NET 10 file-based app gets it from one package line at the top of the file.
  • A class such as Pet maps to documents. Its Id property becomes _id, and the BsonElement attribute gives each property its field name in the document.
  • The driver's filter builder builds the same filter you'd write in mongosh, and a LINQ Where turns into a $match stage the driver sends for you.
  • Calls that talk to the database end in Async and are awaited, as in Node, and InsertOneAsync fills in the new document's Id.
  • Reading a document with a field the class doesn't have stops with an error, unless the class has the BsonIgnoreExtraElements attribute.

Plenty of companies build their back end in C# and .NET, and a job post that asks for "C#, ASP.NET Core and MongoDB" means this lesson's code. The good news: the documents, filters and operators you know don't change. Only the language around them does.

The examples use the Maple Street Pet Adoption Center's pets again. If you don't know C#, read this lesson for the shapes: you'll recognize every filter, and nothing later in the course depends on it. If you know C# and want to run it, install the .NET 10 SDK (winget install Microsoft.DotNet.SDK.10 on Windows, or the installer from dotnet.microsoft.com on a Mac), put the lesson's C# blocks into one file named pets.cs, in order, with the Pet class at the very end, and run it from that folder:

dotnet run pets.cs

One database, another language

Say the shelter's volunteers schedule their shifts with an app a C# team built, and it needs the same pets the Node API uses. Nothing about the data has to change: MongoDB stores the same documents, whichever language wrote them. What changes is the driver. For C#, the official one is the MongoDB.Driver package on NuGet, .NET's package registry, the way npm is Node's. A .NET 10 program in a single file names its packages in a line at the top that starts with #:package (read "hash colon package"), with the exact version:

#:package MongoDB.Driver@3.14.0

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("maple_street_csharp");
await database.DropCollectionAsync("pets");
var pets = database.GetCollection<Pet>("pets");

await pets.InsertManyAsync([
    new Pet { Name = "Biscuit", Species = "dog", Age = 3, Traits = ["good with kids", "house-trained"] },
    new Pet { Name = "Mochi", Species = "cat", Age = 2, Traits = ["calm", "indoor only"] },
    new Pet { Name = "Olive", Species = "cat", Age = 9, Traits = ["calm", "good with kids"] },
    new Pet { Name = "Pickles", Species = "cat", Age = 1, Traits = ["playful", "good with kids"] },
]);

MongoClient and the connection string are the same idea as in Node. The program empties its own practice collection first, so it's safe to run twice, then adds four pets. GetCollection<Pet> (read "get collection of Pet") says each document in pets is a Pet.

A class for a pet

C# wants to know the shape of the data ahead of time, so each kind of document gets a class. It goes at the end of the file:

public class Pet
{
    public ObjectId Id { get; set; }

    [BsonElement("name")]
    public string Name { get; set; } = "";

    [BsonElement("species")]
    public string Species { get; set; } = "";

    [BsonElement("age")]
    public int Age { get; set; }

    [BsonElement("traits")]
    public List<string> Traits { get; set; } = [];

    [BsonElement("status")]
    public string Status { get; set; } = "available";
}

A property named Id becomes the document's _id, by the driver's own rule. C# names properties with a capital letter and the documents use lowercase, so each [BsonElement("name")], an attribute in square brackets, gives the property its field name in the document. Status starts as "available", like Mongoose's default. One catch: when a document has a field the class doesn't, such as the __v Mongoose adds, reading it stops with Element '__v' does not match any field or property of class Pet. Putting [BsonIgnoreExtraElements] above the class tells the driver to skip such fields.

Finding pets: a filter builder or LINQ

The young cats, in mongosh:

db.pets.find({ species: "cat", age: { $lte: 3 } }, { _id: 0, name: 1, age: 1 }).sort({ age: 1 })
[ { name: 'Pickles', age: 1 }, { name: 'Mochi', age: 2 } ]

In C#, Builders<Pet>.Filter builds that same filter, one condition at a time, and & joins two of them with "and". p => p.Species (read "p goes to p dot Species") names a property in a way the compiler checks, so a typo is caught before the program runs:

var filter = Builders<Pet>.Filter.Eq(p => p.Species, "cat")
           & Builders<Pet>.Filter.Lte(p => p.Age, 3);
var youngCats = await pets.Find(filter).SortBy(p => p.Age).ToListAsync();
foreach (var pet in youngCats)
{
    Console.WriteLine(quot;{pet.Name}, {pet.Age}");
}
Pickles, 1
Mochi, 2

C# also has LINQ, its built-in way of querying any collection of objects. The driver turns a LINQ query into MongoDB's own, and printing the query shows what it sends:

var query = pets.AsQueryable().Where(p => p.Species == "cat" && p.Age <= 3);
Console.WriteLine(query.Count());
Console.WriteLine(query);
2
maple_street_csharp.pets.Aggregate([{ "$match" : { "species" : "cat", "age" : { "$lte" : 3 } } }])

There's your filter, inside a $match stage from The Aggregation Pipeline: Data on a Conveyor Belt.

Adding a pet: InsertOneAsync

Every call that talks to the database ends in Async and is awaited, the way await works in Node:

var waffles = new Pet { Name = "Waffles", Species = "dog", Age = 4, Traits = ["good with kids"] };
await pets.InsertOneAsync(waffles);
Console.WriteLine(quot;{waffles.Name}: {waffles.Id}, {waffles.Status}");
Console.WriteLine(await pets.CountDocumentsAsync(FilterDefinition<Pet>.Empty));
Waffles: 6afca2cc51066affc0e67bf7, available
5

InsertOneAsync fills in the new Id, as insertOne gives back an insertedId. Your id will be different. In mongosh, Waffles looks like any other document:

db.pets.findOne({ name: "Waffles" })
{
  _id: ObjectId('6afca2cc51066affc0e67bf7'),
  name: 'Waffles',
  species: 'dog',
  age: 4,
  traits: [ 'good with kids' ],
  status: 'available'
}
mongosh C#
db.pets database.GetCollection<Pet>("pets")
{ species: "cat", age: { $lte: 3 } } Builders<Pet>.Filter.Eq(...) & Builders<Pet>.Filter.Lte(...), or a LINQ Where
.find(...).sort({ age: 1 }) await pets.Find(filter).SortBy(p => p.Age).ToListAsync()
insertOne(...) await pets.InsertOneAsync(pet)
countDocuments({}) await pets.CountDocumentsAsync(FilterDefinition<Pet>.Empty)

Check yourself

2 questions to try on the lesson page.

So what

A filter is a filter, whichever language sends it. With the table above, a C# data layer reads like the mongosh you already know.

Key terms

Related