MongoDB数组-原子更新或推送元素 [英] MongoDB arrays - atomic update or push element

查看:75
本文介绍了MongoDB数组-原子更新或推送元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有以下文档.

I have following document in MongoDB.

{
    "_id" : ObjectId("521aff65e4b06121b688fabc"),
    "user" : "abc",
    "servers" : [
        {
            "name" : "server1",
            "cpu" : 4,
            "memory" : 4
        },
        {
            "name" : "server2",
            "cpu" : 6,
            "memory" : 6
        },
        {
            "name" : "server3",
            "cpu" : 8,
            "memory" : 8
        }
    ]
}

基于某些事件,我必须更新现有服务器的cpu和memory字段,或者如果阵列中不存在新服务器,则向该阵列中添加新服务器.目前,我分两个步骤执行此操作.首先检查服务器在阵列中是否已经存在.如果是,请更新cpu和memory字段.否则,将新的子文档推送到阵列中.由于应用程序的多线程性质,有时会将同一台服务器多次添加到阵列中.是否有任何原子运算符可以执行以下两个操作(类似于$setOnInsert运算符):

Based on certain events, I have to either update the cpu and memory fields of an existing server or add a new server to the array if it does not exist in the array. Currently, I am performing this operation in two steps. First check whether the server already exist in the array. If yes, update cpu and memory fields. Else, push a new sub-document in the array. Due to multi threading nature of the application, sometimes same server is added to the array multiple times. Is there any atomic operator to perform the following two operations (similar to $setOnInsert operator):

  1. 如果数组中存在元素,请更新其字段.
  2. 如果元素不存在于数组中,请推送新元素.

注意:在上述情况下,运算符$addToSet不起作用,因为cpu或内存的值可能不同.

Note: Operator $addToSet is not working in the above case as the value of cpu or memory can be different.

推荐答案

我认为您可以使用 findAndModify()进行此操作,因为它提供了原子更新. 但是您的文档结构不合适. 如果您可以将文档更改为此(即,serverID成为数组的键):

I think you can use findAndModify() to do this as it provides atomic update. But your document structure is not appropriate. If you can change your document to this (i.e, serverID become the key of array):

{
    "_id" : ObjectId("521aff65e4b06121b688fabc"),
    "user" : "abc",
    "servers" : {
       "server1" : {
            "cpu" : 4,
            "memory" : 4
        },
        "server2" : {
            "cpu" : 6,
            "memory" : 6
        },
        "server3" : {
            "cpu" : 8,
            "memory" : 8
        },
    }
}

然后,您可以使用一个原子命令 findAndModify()进行更新,而无需使用两个单独的 find() update() :

Then you can use one atomic command findAndModify() to update without the need of using two separate find() and update():

db.collection.findAndModify
(
 {query:
    {"_id" : ObjectId("521aff65e4b06121b688fabc")}, 
  update: 
    {$set: {"servers.server4": {"cpu":5, "memory":5 }}}, 
  new: true}
)

使用此选项时,如果servers.server4不存在,则将其插入,否则进行更新.

When using this, if servers.server4 does not exist, it will be inserted, otherwise updated.

这篇关于MongoDB数组-原子更新或推送元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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