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 actu开发者_运维问答al class instead of mongodb cursor.
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");
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 ;
}
精彩评论