Search code examples
c#mongodbmongodb-.net-driver

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


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.


Solution

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