使用Mongo查询通过ID更新数组元素 [英] Update array element by id with mongo query
问题描述
是否存在查询将sc从15更新为id为2的数组元素的_id 1为17?我在mongodb中有这个结构:
Is there a query to update sc from 15 to let's say 17 for array element with id 2 for _id 1? I've this structure in mongodb:
{ _id: 1,
lb: [
{
id: 2,
sc: 15
},
{
id: 3,
sc: 16
}
]
}
{ _id: 2,
lb: [
{
id: 5,
sc: 34
},
{
id: 6,
sc: 12
}
]
}
我还有一个:有没有一种方法可以像您刚才所说的那样编写要更新的查询,如果没有带有更新ID的数组元素,请插入一个新的查询.我不想进行两个查询-首先检查元素是否存在并更新它,其次如果没有则追加它.最好将它附加到一个查询中.谢谢. – user3045201 1小时前
I have one more: is there a way to write a query to update as you just said and if there is no array element with updated id, insert a new one. I don't want to make two queries - first to check if element exist and update it, second to append it if there is no such. It would be nice to append it in one query. Thanks. – user3045201 1 hour ago
推荐答案
您可以使用以下查询对其进行更新:
You can update it using the following query :
db.myCollection.update({"_id" : 1, "lb.id" : 2},{$set : {"lb.$.sc" : 17}})
AFAIK,无法在单个查询中执行所需的操作.您必须分别对每个查询进行查询.
AFAIK, It is not possible to do what you want in a single query. You have to make seperate queries for each of them.
这篇关于使用Mongo查询通过ID更新数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!