如果存在则更新数组中的元素,否则在MongoDb中的该数组中插入新元素 [英] Update element in array if exists else insert new element in that array in MongoDb
问题描述
我在MongoDB中具有一组元素数组,如下所示:
I'm having group of array of element in MongoDB as given below :
{
"_id" : 5,
"quizzes" : [
{
"wk" : 1,
"score" : 10
},
{
"wk" : 2,
"score" : 8
},
{
"wk" : 3,
"score" : 5
}
],
"play" : [
{
"wk" : 2,
"score" : 8
},
{
"wk" : 3,
"score" : 5
}
]
}
我正在尝试在数组中插入新记录(如果不存在),并且如果该数组中存在记录,则更新该数组记录. 以下是我的MongoDB查询.
I am trying insert new record in array if not present and if record present in that array then update that array record. Below is my MongoDB query.
db.push.update(
{ _id: 5 },
{ $push: { "quizzes": {"wk" : 6.0,"score" : 8.0},"play": {"wk" : 6.0,"score" : 8.0} } }
)
每次执行此查询时,它都会在数组中插入新记录,但是我想如果记录存在,则更新该数组.
Every time when i execute this query it inserts new record in array but i want if record present then update that array.
推荐答案
使用 $addToSet
而不是$push
.
db.push.update(
{ _id: 5 },
{ $addToSet: { "quizzes": {"wk": 6.0, "score": 8.0}, "play": {"wk": 6.0, "score": 8.0} } }
)
没有一种简单的内置方法可以通过特定属性在数组字段中进行条件子文档更新.但是,有一个小技巧可以通过依次执行两个命令来完成这项工作.
There is no simple built-in approach for conditional sub-document update in an array field, by specific property. However, a small trick can do the job by executing two commands in sequence.
例如:如果要使用对象{ "wk": 7.0, "score": 8.0 }
更新quizzes
字段,可以分两个步骤进行操作:
For example: If we want to update the quizzes
field with the object { "wk": 7.0, "score": 8.0 }
, we can do it in two steps:
步骤1::$pull
从quizzes
数组中的"wk": 7.0
中删除子文档. (如果找不到匹配的子文档,则不会发生任何事情..)
Step-1: $pull
out sub-documents from the quizzes
array where "wk": 7.0
. (Nothing happens if matching sub-document not found).
db.push.update(
{ _id: 5 },
{ $pull: { "quizzes": { "wk": 7.0 } } }
)
第2步: $addToSet
子文档.
db.push.update(
{ _id: 5 },
{ $addToSet: { "quizzes": {"wk": 7.0, "score": 8.0} } }
)
您可以使用 bulk.find().update()
You can combine the above two update commands using the bulk.find().update()
这篇关于如果存在则更新数组中的元素,否则在MongoDb中的该数组中插入新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!