Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"));

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

like image 855
Kuroro Avatar asked Jul 06 '11 07:07

Kuroro


2 Answers

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");
like image 143
Andrew Orsich Avatar answered Nov 15 '22 12:11

Andrew Orsich


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 ;
}
like image 22
DhruvPathak Avatar answered Nov 15 '22 14:11

DhruvPathak