如何更新MongoDB中的文档&在C#中更改from_id之外的所有属性

时间:2018-05-09 23:47:50

标签: c# mongodb bson

public class UserObject
{
    public ObjectId _id { get; set; }// Self generated
    public ulong UserID { get; set; } // Self generated
    public string Username { get; set; }
    public string CharClass{ get; set; }
    public int CharLevel { get; set; }
    public int CharColour { get; set; }
}

我想只更新Username,CharClass,CharLevel& CharColour。

我目前有这个:

var client = new MongoClient(DBString);
var database = client.GetDatabase("UserLists");
var collection = database.GetCollection<UserObject>(Convert.ToString(GuildId));

var filter = Builders<UserObject>.Filter.Eq(s => s.Username, newUserName);

var UpdatedUserObject = new UserObject
{
    UserID = UserId,
    Username = newUserName,
    CharClass = newCharClass,
    CharLevel = newCharLevel,
    CharColour = newCharColour 
};

collection.ReplaceOneAsync(filter, UpdatedUserObject);

如果你有任何建议值得赞赏,我已经得到了添加工作,我似乎无法获得更新,谢谢!

1 个答案:

答案 0 :(得分:0)

我最终做了:

var client = new MongoClient(DBString);
var database = client.GetDatabase("UserLists");
var collection = database.GetCollection<UserObject>(Convert.ToString(GuildId));

var filter = Builders<UserObject>.Filter.Eq(s => s.Username, newUserName);

var UpdatedUserObject = new UserObject
{
    UserID = UserId,
    Username = newUserName,
    CharClass = newCharClass,
    CharLevel = newCharLevel,
    CharColour = newCharColour 
};

collection.ReplaceOne(filter, UpdatedUserObject);

然后它给了我一个问题,它试图更新_id所以我使用这个堆栈溢出来放置[BsonIgnoreIfDefault]所以它没有尝试更新:

Unable to use BsonIgnoreIfDefault for property of type long

public class UserObject
{
    [BsonIgnoreIfDefault]
    public ObjectId _id { get; set; }// Self generated
    public ulong UserID { get; set; } // Self generated
    public string Username { get; set; }
    public string CharClass{ get; set; }
    public int CharLevel { get; set; }
    public int CharColour { get; set; }
}

在修复此问题后,我发现问题是我通过了错误的用户名,因此它从未匹配过&amp;因此没有找到任何更新,只是我真的很蠢,谢谢你的帮助