所以我在我的数据库中有这个文件,如下所示
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 15,
"settings": {
"music": 1,
"sfx": 0
}
}
我有这种方法只更新文档中的特定字段
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)
);
}
如果我执行像
这样的命令,它可以正常工作setPlayerDataField("KingSlizzard",{"credits": 20});
这将导致像这样的文件
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 20,
"settings": {
"music": 1,
"sfx": 0
}
}
学分的价值现在是20码!这是理想的。
但是,如果我执行此命令......
setPlayerDataField("KingSlizzard",{"settings": {"music":0}});
这将导致像这样的文件
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 20,
"settings": {
"music": 0
}
}
我想要做的只是将设置/音乐值设置为0.由于我们丢失了sfx值,因此不需要此结果。
所以我的问题是,如何在不替换整个子对象本身的情况下更新子对象中的值?
答案 0 :(得分:0)
要设置子文档的特定属性,您需要使用dot notation。在你的例子中,你的预期不起作用,你想把它写成:
setPlayerDataField("KingSlizzard", {"settings.music": 0});
请参阅MongoDB文档中的example。
指定< field>在嵌入文档或数组中,使用点表示法。