我有以下“ 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 }
)
它引发错误。如何使其工作?谢谢
答案 0 :(得分:1)
例如:
updateOne({
"_id": ObjectId('1000'),
"products._id": ObjectId('1002')
},{
$set: {"products.$.name": 'ProdBB' } // include other fields here
});
);