首页 文章

MongoDB LinQ“Select”方法是否真的只能检索字段的子集?

提问于
浏览
2

在互联网上搜索如何使用C#官方驱动程序(但使用LinQ作为基础架构)检索MongoDB中的字段子集,我发现如何在MongoDB shell中执行此操作 .

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

然后,我在C#LinQ Tutorial中找到了 Select 方法,它相当于:

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

但是,该教程说该方法“用于从匹配的文档中投射新的结果类型” .

如何确保此方法仅检索字段的子集而不检索整个结果,然后仅选择子集到新对象中?

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

2 回答

  • 4

    驱动程序当前不检索字段的子集 . 如果您需要该功能,则需要手动完成 . 此功能的票证位于:https://jira.mongodb.org/browse/CSHARP-456 . 如果您需要,请随时留下反馈或投票 .

  • 1

    这是作弊......但是:

    //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();
    

相关问题