Read documents

Find a document

To search for a document in MongoDB you use the Find method on a IMongoCollection<T> reference. Find method accepts a FilterDefinition<T> parameter where T is the collection's type.

IMongoCollection<T>.Find(FilterDefinition<T> filter)

Filters can be created using the Builders<T>.Filter definition builder which contain multiple filters. The following example finds a user document based on its Id. It does this using the equality filter Eq<T> on the id field.

ReadDocuments.cs
// Get the collection
var personsCollection = usersDatabase.GetCollection<User>("users");

// Create an Equality Filter Definition
var personFilter = Builders<User>.Filter
    .Eq(person => person.Id, appPerson.Id);

// Find the document in the collection    
var personFindResult = await personsCollection
    .Find(personFilter).FirstOrDefaultAsync();

Notice that when filter used with BsonDocument, _id field name used instead of Id which is the property name on the User class. When you use Builders<User>.Filter this is done automatically for you by the driver, based on the Id serialization settings

Find multiple documents

To search for multiple documents follow the same process but this time use the ToList method. The following example finds all documents with female gender.

ReadDocuments.cs
// Get the collection
var personsCollection = usersDatabase.GetCollection<User>("users");

// Create an equality filter on a user's gender
var femaleGenderFilter = Builders<User>.Filter
    .Eq(person => person.Gender, Gender.Female);
    
// Find all documents having female gender
var females = await personsCollection
    .Find(femaleGenderFilter).ToListAsync();

Last updated