Reputation: 179
I read in mongo db doc that I can use also LINQ but I don't understand some thing about it.
For example, if I write:
var result = collection.Find(filter);
and
var result = collection.AsQueryable()
.Where(x => x.Foo == 114)
What is better?
LINQ filters on based of entire collection? Before I get entire collection and then it filters? Or before filters and it give me the collection already filtered?
Upvotes: 5
Views: 2698
Reputation: 8498
Both do pretty much the same.
The LINQ API is a wrapper over the Collection API.
From briefly studying the sources of mongo-csharp-driver, I can see that the LINQ version calls either Collection.FindAs(...) or Collection.Distinct(...). It constructs the IMongoQuery
passed in the query
parameter, based on the LINQ expression. For that, it uses the query builder API (the Query class), such as Query.EQ
What is better?
It depends.
class
explicitly containing document properties). In such a case, using LINQ would be a struggle, and the raw Collection API would be a better choice. LINQ filters on based of entire collection? Before I get entire collection and then it filters? Or before filters and it give me the collection already filtered?
Since LINQ API implements IQueryable
and not just IEnumeable
, all enumerable methods (such as Where
or OrderBy
) are not actually called, but rather are translated during compilation into code that builds expression trees. At runtime, the expression trees are built and passed to underlying query provider (implemented by MongoDB Driver in this case). The query provider translates expression trees into regular MongoDB queries and executes them through the regular MongoDB API.
See How to: Use Expression Trees to Build Dynamic Queries for more details.
So the query is actually executed in the database, and only the processed (filtered, ordered, or projected) results are returned to the application.
Yet, using LINQ API implies some performance overhead, because in addition to running the query, LINQ API also:
In many cases this overhead is neglectable, but it depends on your requirements.
Upvotes: 7