Mongodb -- include or exclude certain elements with c# driver
Update: With new driver version (1.6+) you can avoid fields names hard-coding by using linq instead:
var users = usersCollection.FindAllAs<T>()
.SetFields(Fields<T>.Include(e => e.Id, e => e.Name));
You can do it via SetFields
method of mongodb cursor:
var users = usersCollection.FindAllAs<T>()
.SetFields("_id") // include only _id
.ToList();
By default SetFields
includes specified fields. If you need exclude certain fields you can use:
var users = usersCollection.FindAllAs<T>()
.SetFields(Fields.Exclude("_id")) // exclude _id field
.ToList();
Or you can use them together:
var users = usersCollection.FindAllAs<T>()
.SetFields(Fields.Exclude("_id") // exclude _id field
.Include("name")) // include name field
.ToList();
Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.
The currently recommended way to include or exclude certain members is to use the Project
method on the IFindFluent
you get from Find
.
You can either pass a lambda expression:
var result = await collection.Find(query).Project(hamster => hamster.Id).ToListAsync();
Or use the projection builder:
var result = await collection.Find(query)
.Project<Hamster>(Builders<Hamster>.Projection.Include(hamster => hamster.Id))
.ToListAsync();
var result = await collection.Find(query)
.Project<Hamster>(Builders<Hamster>.Projection.Exclude(hamster => hamster.FirstName).
Exclude(hamster => hamster.LastName))
.ToListAsync();