Amey
Amey

Reputation: 1296

Projection with AsQueryable in MongoDB C# driver 2.2

I am trying my hands at MongoDB C# driver version 2.2. I am trying to use projection as I do not want to retrieve all the elements in the document. I found one way to do that is to use project operator along with find operator, something like this:

collection.Find(key => key.Index == 1).Project<MyClass>(Builders<MyClass>.Projection.Include(key => key.Name).Include(key => key.Index)). ToEnumerable ();

However I am interested in using AsQueryable API along with where operator, something like this:

collection.AsQueryable().Where(key => key.Index == 1);

Is it possible to use projection in above case? If I use select operator, will it have same effect as projection? Or will still fetch all the elements from database server and then select specified elements in the application server?

Upvotes: 5

Views: 3261

Answers (1)

ocuenca
ocuenca

Reputation: 39346

Yes, it is possible. If you add a Select (Select(i => new { i.Name, i.Index})) to your query and call ToString method at the end, you'll see that Linq provider generates an aggregation pipeline with two operations (a $match and a $project):

var query=collection.AsQueryable().Where(key => key.Index == 1).Select(k=>new {k.Name,k.Index});
var aggregate= query.ToString();

In sumary, yes, a Select generates a $project operation.

About your other questions, your query is not going to be executed until you call a method like ToList (that is going to fetch the result of your query to memory) or when you iterate over the result.

Upvotes: 10

Related Questions