MongoDB更新并插入数组

时间:2020-02-15 01:19:58

标签: mongodb mongodb-query

我有一个mongo文档,如下所示:

{
  "ITEMS": [
    {
      "BUKRS": "1000",
      "GLACC": "476000",
      "NETWR": 100
    }
  ],
  "EXCEPTIONS": [
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": false,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    }
  ]
}

我需要实现的是在一个mongo查询中,设置所有EXCEPTIONS.$.CURR:false并将一个新对象插入到主要包含CURR : true EXCEPTIONS 数组中。

1 个答案:

答案 0 :(得分:1)

对于MongoDB版本的> = 3.2,您可以使用.bulkWrite()在一个数据库调用中完成:

db.collection.bulkWrite([{
    updateOne: {
        "filter": {}, // If you've any filters to match a doc give it here
        "update": { $set: { "EXCEPTIONS.$[].CURR": false } } // $[] operator updates all elements in an array.
    }
}, {
    updateOne: {
        "filter": {},
        "update": {
            $push: {
                "EXCEPTIONS": {
                    "CURR": true,
                    "EVENT": "WEB",
                    "DATE_TIME": "New_Time"
                }
            }
        }
    }
}])

数据库中的文档:

/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [ 
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [ 
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }, 
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }, 
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }
    ]
}

响应:

/* 1 */
{
    "acknowledged" : true,
    "deletedCount" : 0.0,
    "insertedCount" : 0.0,
    "matchedCount" : 2.0, // It's 2 as it modified array/doc twice
    "upsertedCount" : 0.0,
    "insertedIds" : {},
    "upsertedIds" : {}
}

数据库结果:

/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [ 
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [ 
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }, 
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }, 
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }, 
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "New_Time"
        }
    ]
}