MongoDB更新并插入数组

2020-02-15 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然后将一个新对象插入到EXCEPTIONS数组中,其中大部分为CURR : true

Answers

您可以使用.bulkWrite()在MongoDB版本> = 3.2一个数据库调用中完成此操作:

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"
                }
            }
        }
    }
}])

DB中的文档:

/* 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"
        }
    ]
}

Related