MongoDB:upsert子文档数组

时间:2019-03-05 17:08:19

标签: mongodb upsert subdocument

我有以下“ SaleOrderCol”集合:

{
  _id: ObjectId('1000'),
  products: [
              { _id: ObjectId('1001'), name: 'ProdA', qty: 5},
              { _id: ObjectId('1002'), name: 'ProdB', qty: 10}
            ]
},
{
  _id: ObjectId('2000'),
  products: [
              { _id: ObjectId('2001'), name: 'ProdA', qty: 5},
              { _id: ObjectId('2002'), name: 'ProdC', qty: 10}
            ]
}

我想做一个upsert来更改子文档的名称和数量(1002),然后尝试以下操作:

SaleOrderCol.updateOne(
    { 
      "_id": ObjectId('1000'),
      "products._id": ObjectId('1002')
    },
    {
      $set : { "products": { name: 'ProdBB', qty: 15 }
    },
    { upsert: true }
)

它引发错误。如何使其工作?谢谢

1 个答案:

答案 0 :(得分:1)

使用$ positional operator

例如:

updateOne({ 
      "_id": ObjectId('1000'),
      "products._id": ObjectId('1002')
    },{
       $set: {"products.$.name": 'ProdBB' } // include other fields here
   });
);