How to use SetField in FindOne in MongoDB For C# Driver

后端 未结 2 363
抹茶落季
抹茶落季 2020-12-10 15:47

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).SetField         


        
相关标签:
2条回答
  • 2020-12-10 16:27

    SetFields method of MongoCursor.

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

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

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

    And use it like this:

     var user = Users.FindOne<User>("Password");
    
    0 讨论(0)
  • 2020-12-10 16:35

    I am not sure about exclusion in findOne. But instead of findOne, you can better use find with limit 1 . That would return a cursor, which will ofcourse support exclusion of a field. Something like :

    var theCursor = Users.Find(query).SetFields(Fields.Exclude("Password")).SetLimit(1) ;
    var myItem = null;
    foreach (var item in cursor) {
        myItem = item ;
    }
    
    0 讨论(0)
提交回复
热议问题