Mongodb — include or exclude certain elements with

2019-01-13 04:45发布

问题:

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.

回答1:

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


回答2:

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


回答3:

Update You could use a projection and FindAsync which returns a cursor and doesn't load all documents at once unlike Find. You can also set a sort order and limit for number of documents returned.

    var findOptions = new FindOptions<BsonDocument>();

    findOptions.Projection = "{'_id': 1}";

    // Other options
    findOptions.Sort = Builders<BsonDocument>.Sort.Ascending("name");           
    findOptions.Limit = int.MaxValue;

    var collection = context.MongoDatabase.GetCollection<BsonDocument>("yourcollection");   

    using (var cursor = collection.FindSync("{name : 'Bob'}", options))
    {
        while (cursor.MoveNext())
        {
            var batch = cursor.Current;
            foreach (BsonDocument document in batch)
            {
                // do stuff...
            }
        }
    }