Mini Dev 1
Mini Dev 1

Reputation: 179

MongoDb driver c# query optimization

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

Answers (1)

felix-b
felix-b

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.

  • If you have types in C# code that represent structure of documents in the database, then you're likely to benefit from the LINQ API. You will benefit from strong typing, better readability, and you won't miss a renamed identifier whose name was passed as a string.
  • If you have dynamic structure of data, which has no concrete representation in code (you have some kind of metadata about a document, but not a 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:

  • builds expression trees to pass them to query provider
  • visits expression trees to translate them into native query

In many cases this overhead is neglectable, but it depends on your requirements.

Upvotes: 7

Related Questions