首页 > 解决方案 > MongoDB:插入子文档数组

问题描述

我有以下“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 }
)

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

标签: mongodbupsertsubdocument

解决方案


使用$位置运算符

例如:

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

推荐阅读