MongoDB: upsert 子文档数组

MongoDB: upsert sub document array

我有以下 'SaleOrderCol' collection:

{
  _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}
            ]
}

我想执行更新插入以更改子文档 (1002) 的名称和数量,然后尝试以下操作:

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

它抛出错误。如何让它工作?谢谢

使用$ positional operator

例如:

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