βοΈProject
Include and Exclude
// Create a ProjectDefinition<T>
var definition = Builders<T>.Projection
.Exclude(doc => doc.<field1>)
.Include(doc => doc.<field2>)
...
.Include(doc => doc.<fieldN>)
// Get results
var simpleProjectionResults = await usersCollection
.Find(Builders<User>.Filter.Empty)
.Project(simpleProjection) // projection stage
.ToListAsync();var collection = database
.GetCollection<User>(Constants.UsersCollection);
// exclude id, return only gender and date of birth
var simpleProjection = Builders<User>.Projection
.Exclude(u => u.Id)
.Include(u => u.Gender)
.Include(u => u.DateOfBirth);
var simpleProjectionResults = await usersCollection
.Find(Builders<User>.Filter.Empty)
.Project(simpleProjection)
.ToListAsync();var bsonCollection = database
.GetCollection<BsonDocument>(Constants.UsersCollection);
var bsonSimpleProjection = Builders<BsonDocument>.Projection
.Exclude("_id")
.Include("gender")
.Include("dateOfBirth");
var bsonSimpleProjectionResults = await bsonCollection
.Find(Builders<BsonDocument>.Filter.Empty)
.Project(bsonSimpleProjection)
.ToListAsync();Include custom fields
Projection with LINQ
Last updated