Reputation: 5462
I've found c# code like this (Collection
is of type MongoCollection<T>
here):
Collection.AsQueryable()
.OrderByDescending(i => i.SomeField)
.Where(i => i.OtherField == "bla-bla")
does not run both sorting (OrderBy) and filtering (Where) on a server as I expected, instead it calls sorting with MongoDb engine and all further filtering is processed on a client side, which takes fair amount of time. That what I've found in Mongodb profiler as a result of the code execution:
"query" : {
"$query" : { },
"$orderby" : {
"SomeField" : -1
}
}
Note $query
is empty. Well, is there any idea over how to make it work on database (both sorting and filtering)?
Upvotes: 2
Views: 1085
Reputation: 218
To order the items, all have to be retrieved, so if you specify that as the first operation I'd expect the behaviour you observed. So you'd have to reverse your statement (as you do in the IMongoQuery
syntax). This can also be done in LINQ syntax, but since Where
returns IEnumerable
, you need an extra cast:
Collection.AsQueryable()
.Where(i => i.OtherField == "bla-bla").AsQueryable()
.OrderByDescending(i => i.SomeField)
Upvotes: 1
Reputation: 5462
Well, one of the resolution I've just found might look like this:
Collection.Find(
Query.And(Query.EQ("OtherField", "bla-bla")).
SetSortOrder(SortBy.Descending("SomeField").ToList()
It builds exactly what I need:
"query" : {
"$query" : {
"OtherField" : "bla-bla"
},
"$orderby" : {
"SomeField" : -1
}
}
However I do not quite like this approach as it makes me to hardcode database field names. Presumably new c# driver 1.6 will let you build same queries using delegates like i => i.OtherField == "bla-bla"
.
Any other approaches?
Upvotes: 1