Using MongoDB C# driver, seems that I'm unable to get the data by AsQueryable with setFields and Where condition only by mongo query. I fetched documents by 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 query1 or query2 executed, c# driver fetches all documents from mongo and then filters it in memory. But I expected that Where condition will be converted to mongo query with fields. Can anyone please explain how to do it correctly?
You using .AsQueryable()
from System.Linq
, because of this it filter everything on a client side. But you need to use .AsQueryable()
from MongoCollection
to filter data in a database. This extension method creates MongoQueryable<T>
.
I believe that 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 use SetFields
you have to use old query syntax:
_col.Find(Query<UserDocument>.EQ(x=> x.Name, "Ken")).SetFields(..).
Also you could use SetFields without magic strings as follow:
cursor.SetFields(Fields<UserDocument>.Include(x=> x.Name, x=> x.Age))
With linq SetFields is done via Select
.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.