标签: gamesparks

更新 MongoDB 文档子对象而不替换

所以我的数据库中有这个文档,如下所示

{
  "_id": {
    "$oid": "59a8668f900bea0528b63fdc"
  },
  "userId": "KingSlizzard",
  "credits": 15,
  "settings": {
    "music": 1,
    "sfx": 0
  }
}
Run Code Online (Sandbox Code Playgroud)

我有这种方法只更新文档中的特定字段

function setPlayerDataField(targetUserId, updateObject) {
    playerDataCollection.update({
            "userId": targetUserId //Looks for a doc with the userId of the player
        }, { $set: updateObject }, //Uses the $set Mongo modifier to set value at a path
        false, //Create the document if it does not exist (upsert)
        true //This query will only affect a single object (multi)
    );
}
Run Code Online (Sandbox Code Playgroud)

如果我执行类似的命令,效果很好

setPlayerDataField("KingSlizzard",{"credits": 20});
Run Code Online (Sandbox Code Playgroud)

它会产生这样的文档

{ …
Run Code Online (Sandbox Code Playgroud)

mongodb gamesparks

6
推荐指数
1
解决办法
1683
查看次数

标签 统计

gamesparks ×1

mongodb ×1