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.
// 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();// Get the collection
var bsonPersonCollection = usersDatabase.GetCollection<BsonDocument>("users");
// Create a bson filter
var bsonPersonFilter = Builders<BsonDocument>.Filter.Eq("_id", appPerson.Id);
// Find a person using a class filter
var bsonPersonFindResult = await bsonPersonCollection
.Find(bsonPersonFilter).FirstOrDefaultAsync();
// alternative for passing a filter argument
bsonPersonFindResult = await bsonPersonCollection
.Find(new BsonDocument("_id", appPerson.Id)).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.
Last updated