Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
Amey Avatar asked Feb 05 '16 16:02

Amey


1 Answers

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.

like image 146
octavioccl Avatar answered Sep 28 '22 12:09

octavioccl