在另一个子文档数组中的猫鼬增量子文档数组值

时间:2020-05-29 21:31:34

标签: mongodb mongoose mongodb-query aggregation-framework

我有一个这样的文件

_id:'111'
products:[
   {
    _id:'pqr'
    nums:[
      {_id:'aaa',
      quantity:50
      },
      {_id:'bbb',
       quantity:50
      }
    ]
   }
]

上面的文档可以像下面这样概括,以便于理解。

   _id
   products: [
      nums: [
        {}, //quantity is in this object
        {}
      ]
   ]

我需要增加nums子文档中的数量值,该值基于产品_document的_id。

到目前为止,这是我尝试过的方法,但是由于我不知道如何捕获nums对象中的_id以便更新该子子文档数组中的特定对象,因此无法正常工作。

Shop.findOneAndUpdate(
       { "_id": '111', "products._id": 'pqr'  },
          {
            "$inc": {
               "products.$[].nums.quantity": 1
            }
    }
)

我该如何实现?

1 个答案:

答案 0 :(得分:1)

在更新操作中使用arrayfilters

db.getCollection("collectionName").findOneAndUpdate(
  { _id: "111" }, // Querying against `_id`, need to convert string to `ObjectId()` or instead use `.findByIdAndUpdate()`
  { $inc: { "products.$[p].nums.$[n].quantity": 1 } },
  {
    arrayFilters: [{ "p._id": "pqr" }, { "n._id": "aaa" }] // Inputs here
  }
  // Use { new : true } Option in mongoose to return updated document
);

输入文档:

{
    "_id" : "111",
    "products" : [ 
        {
            "_id" : "pqr",
            "nums" : [ 
                {
                    "_id" : "aaa",
                    "quantity" : 50
                }, 
                {
                    "_id" : "bbb",
                    "quantity" : 50
                }
            ]
        }, 
        {
            "_id" : "abc",
            "nums" : [ 
                {
                    "_id" : "aaa1",
                    "quantity" : 501
                }, 
                {
                    "_id" : "bbb1",
                    "quantity" : 501
                }
            ]
        }
    ]
}

输出文档:

{
    "_id" : "111",
    "products" : [ 
        {
            "_id" : "pqr",
            "nums" : [ 
                {
                    "_id" : "aaa",
                    "quantity" : 51 // This got incremented
                }, 
                {
                    "_id" : "bbb",
                    "quantity" : 50
                }
            ]
        }, 
        {
            "_id" : "abc",
            "nums" : [ 
                {
                    "_id" : "aaa1",
                    "quantity" : 501
                }, 
                {
                    "_id" : "bbb1",
                    "quantity" : 501
                }
            ]
        }
    ]
}

参考: mongoose's .findByIdAndUpdate()