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

后端 未结 2 365
抹茶落季
抹茶落季 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() {
       return FindAllAs().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(this MongoCollection collection, 
                                   params string[] excludedFields)
        {
            return collection.FindAllAs().SetLimit(1)
                                            .SetFields(excludedFields)
                                            .FirstOrDefault();
        }
    }
    

    And use it like this:

     var user = Users.FindOne("Password");
    

提交回复
热议问题