How would I translate this mongo query to a Query.EQ statement in C#?
db.users.find({name: 'Bob'}, {'_id': 1});
In other words, I don't want everything returned to C# -- Just the one element I need, the _id. As always, the Mongo C# Driver tutorial is not helpful.
To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With