Mongodb -- include or exclude certain elements with c# driver

carlbenson picture carlbenson · Dec 9, 2011 · Viewed 23k times · Source

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.

Answer

Andrew Orsich picture Andrew Orsich · Dec 9, 2011

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