如何在MongoDB中使用SetField在FindOne对于C#驱动程序 [英] How to use SetField in FindOne in MongoDB For C# Driver

查看:655
本文介绍了如何在MongoDB中使用SetField在FindOne对于C#驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用官方的C#驱动程序MongoDB的,我想用SetFields从FindOne查询像查找。

I use offical C# Driver for mongodb, I want to use SetFields from a FindOne query like Find.

var query = Query.EQ("Name", name);
Users.Find(query).SetFields(Fields.Exclude("Password"));

是否有可能做,因为FindOne返回的MongoDB光标的实际类代替。

Is it possible to do that as FindOne return a actual class instead of mongodb cursor.

推荐答案

SetFields MongoCursor的方法。

SetFields method of MongoCursor.

方法FindOne只是包装器MongoCursor并在内部它看起来如此:

Method FindOne just wrapper around MongoCursor and internally it looks so:

public virtual TDocument FindOneAs<TDocument>() {
   return FindAllAs<TDocument>().SetLimit(1).FirstOrDefault();
}

如果你想添加排除字段的功能,它可以简单地添加延伸方法 MongoCollection

If you want add Exclude Fields functionality to it you can simply add extention method for MongoCollection :

public static class MongodbExtentions
{
    public static T FindOne<T>(this MongoCollection collection, 
                               params string[] excludedFields)
    {
        return collection.FindAllAs<T>().SetLimit(1)
                                        .SetFields(excludedFields)
                                        .FirstOrDefault();
    }
}

和使用这样的:

 var user = Users.FindOne<User>("Password");

这篇关于如何在MongoDB中使用SetField在FindOne对于C#驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆