Lesson 3: Querying a MongoDB Collection in C# Applications / Learn

Querying a MongoDB Collection in C# Applications

Review the following code, which demonstrates how to query documents in MongoDB with C#.


Find a Document with FirstOrDefault

In the following example, the Find() command with a LINQ expression matches the AccountID field. The FirstOrDefault() method returns the first or default result.

var account = accountsCollection
   .Find(a => a.AccountId == "MDB829001337")
   .FirstOrDefault();


Find a Document with FindAsync and FirstOrDefault

The FindAsync() command with a LINQ expression matches the AccountID field. The FirstOrDefault() method returns the first or default result. For example:

var accounts = await accountsCollection
   .FindAsync(a => a.AccountId == "MDB829001337");

var account = accounts.FirstOrDefault();


Find a Document with ToList

The Find() command with a LINQ expression matches all documents in the collection. The ToList() method returns a list of results. For example:

var accounts = accountsCollection.Find(_ => true).ToList();


Find a Document with Multiple LINQ Methods

The Find() command with a LINQ expression filters documents by AccountType (in this case, “checking”), sorts the results in descending order by the Balance, skips the first 5 results, and returns only 20 documents due to the limit.

accountsCollection
   .Find(a => a.AccountType == "checking")
   .SortByDescending(a => a.Balance)
   .Skip(5)
   .Limit(20);


Find a Document with the Builders Class

Use the Builders class to match all documents in the collection with an _id field equal to the specified value. For example:

var filter = Builders<BsonDocument>
   .Filter
   .Eq("_id", new    
      ObjectId("62d6e04ecab6d8e1304974ae"));

var document = accountsCollection
   .Find(filter)
   .FirstOrDefault();

Use the Builders class to match all documents in the collection with a balance field greater than 1000. For example:

var filter = Builders<BsonDocument>
   .Filter
   .Gt("balance", 1000);

var documents = await accountsCollection
   .FindAsync(filter);