MongoDB - 在数组中更新或插入对象

问题描述 投票:16回答:5

我有以下收藏

{
    "_id" : ObjectId("57315ba4846dd82425ca2408"),
    "myarray" : [ 
             {
                userId : ObjectId("570ca5e48dbe673802c2d035"),
                point : 5
             },
             {
                userId : ObjectId("613ca5e48dbe673802c2d521"),
                point : 2
             },        
     ]
}

These are my questions

如果用户ID不存在,我想推入数组,它应该附加到数组。如果存在用户ID,则应将其更新为point。

I found this

db.collection.update({
  _id : ObjectId("57315ba4846dd82425ca2408"), "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
},{
   $set: {"myarray.$.point": 10}
})

但是如果userId不存在,则没有任何反应。

and

db.collection.update({
  _id : ObjectId("57315ba4846dd82425ca2408")
},{
  $push: {"myarray": {userId: ObjectId("570ca5e48dbe673802c2d035"), point: 10}}
})

但是如果userId对象已经存在,它将再次推送。

在MongoDB中执行此操作的最佳方法是什么?

mongodb
5个回答
9
投票

试试这个

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)

14
投票

Flying Fisher接受的答案是,现有记录将首先被删除,然后再次被推送。

一种更安全的方法(常识)是首先尝试更新记录,如果找不到匹配,请插入它,如下所示:

// first try to overwrite existing value
var result = db.collection.update(
   {
       _id : ObjectId("57315ba4846dd82425ca2408"),
       "myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
   },
   {
       $set: {"myarray.$.point": {point: 10}}
   }
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
    // record not found, so create a new entry
    // this can be done using $addToSet:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408")
        },
        {
            $addToSet: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
    // OR (the equivalent) using $push:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408"),
            "myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
        },
        {
            $push: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
}

这也应该给(常识,未经测试)性能提高,如果在大多数情况下记录已经存在,则只执行第一个查询。


1
投票

不幸的是,嵌入式阵列无法实现“upsert”操作。操作符根本不存在,因此在单个语句中不可能这样做。因此,您必须执行两个更新操作才能执行所需操作。此外,这两个更新的应用顺序对于获得所需结果也很重要。


0
投票

如果要在数组中更新或插入值,请尝试使用它

db中的对象

key:name,
key1:name1,
arr:[
    {
        val:1,
        val2:1
    }
]

询问

var query = {
    $inc:{
        "arr.0.val": 2,
        "arr.0.val2": 2
    }
}
.updateOne( { "key": name }, query, { upsert: true }

key:name,
key1:name1,
arr:[
    {
        val:3,
        val2:3
    }
]

0
投票

在MongoDB 3.6中,现在可以使用upsert elements in an array

© www.soinside.com 2019 - 2024. All rights reserved.