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();
circle-exclamation

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.

Last updated