Mongodb C # FindAll driver with setFields and AsQueryable

Using the MongoDB C # driver, it seems that I cannot get data using AsQueryable with the setFields and Where parameters only at the request of mongo. I extracted documents for this code

var query = _collection.FindAll().SetFields(fields.MongoFieldsBuilder).AsQueryable(); var query1 = query.Where(d=>d.Name="Ken").ToList(); var query2 = query.Where(d=>d.Age>=2).ToList(); 

So, when query 1 or query2 is executed, the C # driver extracts all documents from mongo and then filters it in memory. But I was expecting the Where clause to be converted to a mongo request with fields. Can someone explain how to do this correctly?

+4
source share
1 answer

You use .AsQueryable() from System.Linq , because of this, it filters everything on the client side. But you need to use .AsQueryable() from MongoCollection to filter the data in the database. This extension method creates a MongoQueryable<T> .

I believe the following should work:

 //or you could use your projection class instead of BsonDocument var query = Items.AsQueryable<BsonDocument>() .Select(x=> new {id = x["_id"].AsObjectId, Name=x["Name"].AsString}); var query1 = query.Where(d=>d.Name == "Ken").ToList(); 

Update:

If you want to use SetFields , you need to use the old query syntax:

 _col.Find(Query<UserDocument>.EQ(x=> x.Name, "Ken")).SetFields(..). 

You can also use SetFields without magic lines as follows:

 cursor.SetFields(Fields<UserDocument>.Include(x=> x.Name, x=> x.Age)) 

Using linq, SetFields is done through Select .

Hope this helps.

+5
source

All Articles