如果存在则更新数组中的元素,否则在 MongoDb 的该数组中插入新元素 [英] Update element in array if exists else insert new element in that array in MongoDb

查看:27
本文介绍了如果存在则更新数组中的元素,否则在 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:

第一步: $pullquizzes 数组中取出子文档,其中 "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()

这篇关于如果存在则更新数组中的元素,否则在 MongoDb 的该数组中插入新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆