如何使用 MongoDB C# 将新对象插入(推送)到嵌套数组中?

How to insert (push) a new object into a nested array using MongoDB C#?

{
    "_id" : "",
    "Username" : "",
    "Points" : 0,
    "CompletedAchievements" : [],
    "ActiveAchievements" : [],
    "Kudos" : [],
    "Teams" : [],
    "UserType" : "Standard"
}

这是我要插入的记录。 我正在尝试将以下对象添加到 ActiveAchievements 数组中。

{
    "_id": "my new id",
    "progress": 10
}

我希望将其添加到我的数据库中的记录(具有我可以通过其获取的唯一 ID)中已存在的 Active Achievements 数组中。以及未来更多。

我如何使用 MongoDb.Driver 执行此操作?在 C# 中

假设有一个名为 users 的集合,文档的 Username 为“John Doe”,以下代码会将 { "_id": "my new id", "progress": 10 } 添加到 ActiveAchievements 数组字段。

var collection = database.GetCollection<BsonDocument>("users");
var filter = Builders<BsonDocument>.Filter.Eq("UserName", "John Doe");
var update = Builders<BsonDocument>.Update
                                   .Push<BsonDocument>(
                                        "ActiveAchievements", 
                                        new BsonDocument("_id", "my new id").Add("progress", 10));
var result = collection.UpdateOne(filter, update);
Console.WriteLine(result.ModifiedCount); // should print 1, as one document is updated

参考文献: