这个问题在这里已有答案:
我有一个具有如下结构的集合
{ "_id" : "MHBk8q96vpuRYrAdn",
"circles" : {
"guests" : 3,
"properties" : [
{
"position" : { "x" : 146, "y" : 70.5207970},
"name" : "circle-1"
},
{
"position" : { "x" : 200, "y" : 85},
"name" : "circle-2"
}
],
"tables" : 1
}
}
我需要能够更新circles.properties.position的位置(如果它按名称存在),或者如果不存在则添加新条目 . 例如,更新“circle-1”的位置,因为它存在,但为“circle-3”添加一个带有名称和位置的新数组项 . 是否有可能实现这一目标?到目前为止,我只能使用$ push来推送数组,而且我已经弄乱了$(查询)运算符但没有成功 . 谢谢 .
1 回答
自MongoDB doesn't support upserts to arrays以来,这可能很棘手 . 您可以尝试以下内容:
Edit
如果你不能使用
save
和update
与upsert
选项替换上面发布的if-else
块这样的东西应该做的伎俩: