如果项目不存在,则更新数组中的条目或添加到数组 [英] Update entry in an array or add to array if item doesn't exist
问题描述
我有一个具有如下结构的集合
I have a collection that has a structure that looks like the following
{ "_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 推送到数组上,并且我在使用 $(query) 运算符时没有成功.谢谢.
I need to be able to either update the position of circles.properties.position if it exists by name, or add a new entry if it does not. For example, update the position of "circle-1" since it exists, but add a new array item for "circle-3" with a name and position. Is it possible to achieve this? So far I have only been able to push onto the array using $push, and I have messed around with the $(query) operator with no success. Thanks.
推荐答案
自从 MongoDB 不支持对数组进行更新插入 这可能很棘手.您可以尝试以下操作:
Since MongoDB doesn't support upserts to arrays it can be tricky. You can try something like below:
var query = {};
new_circle = { "position" : { "x" : -1, "y" : -1}, "name" : "circle-1" };
db.foo.find(query).forEach(
function(doc) {
// Find index of 'circle-1'
i = doc.circles.properties.map(
function(el) { if (el.name == 'circle-1') return 1; else return -1;}
).indexOf(1);
// Update if circle-1 in circles-properties
if (i != -1) {
doc.circles.properties[i] = new_circle;
}
// If not push new
else {
doc.circles.properties.push(new_circle);
}
db.foo.save(doc);
}
)
编辑
如果您不能使用 save
和 update
和 upsert
选项替换上面张贴的 if-else
块像这样应该可以解决问题:
If you cannot use save
and update
with upsert
option replacing if-else
block posted above with something like this should do the trick:
if (i != -1) {
db.foo.update(
{"_id" : doc._id, "circles.properties.name": "circle-1"},
{$set: {"circles.properties.$.position": new_circle.position}}
}
else {
db.foo.update(
{"_id" : doc._id},
{$push: {"properties": new_circle }}
)
}
这篇关于如果项目不存在,则更新数组中的条目或添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!