mongodb - 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 }
)
它抛出错误。如何让它工作?谢谢
解决方案
使用$
位置运算符
例如:
updateOne({
"_id": ObjectId('1000'),
"products._id": ObjectId('1002')
},{
$set: {"products.$.name": 'ProdBB' } // include other fields here
});
);
推荐阅读
- amazon-web-services - AWS Lambda@Edge 的缓存选项
- javascript - jQuery UI,响应式调整最后一个 div
- openapi - 在属性中限制 openapi 类型的正确方法是什么?
- ios - 如何在 Swift 中使用滑块值更改 kCIInputBrightnessKey,无论滑块获得什么值,我都会得到白色或黑色图片
- machine-learning - 用户行为预测/分析
- php - Laravel:如果 foreach 为空
- python-3.x - 发送 HEX 命令并回读到 rfid reader tcp
- c++ - 从多个函数写入文件并替换值 C++
- angular - 如何在 ionic 4 中禁用侧边菜单?
- python-3.x - 在 pandas 中识别两个不同大小的数据帧中的公共列值