MongoDB LinQ “Select” method will really retrieve

2019-02-15 13:00发布

Searching across the internet how to retrieve a subset of fields in MongoDB, using C# official driver (but using LinQ as the base architecture) I found how to do this in MongoDB shell.

// selecting only "field" of a collection
db.collection.find( { field : 'value' }, { field: 1 } ); 

Then, I found at C# LinQ Tutorial the Select method, which is equivalent to this:

collection.AsQueryable<T>().Select(x => new { x.field });

However, the tutorial says the method "is used to project a new result type from the matching documents".

How to ensure this method will retrieve only the subset of fields and not the entire result and then select only the subset into a new object?

Will the driver build the query command before retrieve the results?

2条回答
beautiful°
2楼-- · 2019-02-15 13:34

The driver does not currently retrieve a subset of the fields. If you need that functionality, you'll need to do it manually. The ticket for this functionality is here: https://jira.mongodb.org/browse/CSHARP-456. Feel free to leave feedback or vote it up if you need this.

查看更多
SAY GOODBYE
3楼-- · 2019-02-15 13:34

This is cheating... but:

//This actual implementation is untested and may contain small errors.
//The helper method has been tested and *should* work.

public static IMongoQuery GetMongoQuery<T>(this IQueryable<T> query)
{
    return ((MongoQueryable<T>)query).GetMongoQuery();
}

var temp =
    from x in DB.Foo.AsQueryable<Test>()
    where x.SomeField > 5;
    select (x.OtherField);

return temp.GetMongoQuery().ToJson();
查看更多
登录 后发表回答