I am using the official MongoDB C# driver
So I have this code
MongoCollection<MyClass> collection = ...;
var cursor = collection.FindAll();
cursor.Fields = Fields.Include("LastModified", "Name");
foreach (var result in cursor.Select(y => new
{
y.Name,
y.LastModified,
}))
I want to know if cursor.Fields = Fields.Include("LastModified", "Name");
is required if those fields are being defiend as part of select. i.e. is the linq provider for mongodb smart enough to optimise the query?
There are two parts to the answer:
First, the LINQ implementation in the 1.4 release of the C# driver does not attempt to limit the fields returned from the server. The entire document is always returned, even if a projection later only uses part of it. We plan to optimize this in future releases, but it's not as easy as it sounds.
Second, you aren't actually using a LINQ query, at least not a LINQ to MongoDB query. As your code is written you are fetching the entire collection to the client (that's what FindAll does) and then using Select locally against the retrieved values. A similar LINQ query against MongoDB would be written like this:
var query = from y in collection.AsQueryable<MyClass>()
select new { y.Name, y.LastModified };
foreach (var result in query)
{
// process result
}