我有这个文件结构
{
"_id": <OBJECT_ID>,
"orders": [
{
"userId": 1,
"handleName": "John Doe",
"orderAmount": 3,
"others": [
{
"userId": 1,
"handleName": "John Doe"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 2,
"handleName": "Maria Gigante",
"orderAmount": 2,
"others": [
{
"userId": 1,
"handleName": "John Doe"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 1,
"handleName": "John Doe",
"orderAmount": 4,
"others": [
{
"userId": 1,
"handleName": "John Doe"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 3,
"handleName": "John Doe",
"orderAmount": 4,
"others": [
{
"userId": 1,
"handleName": "John Doe"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
}
]
}
我想更新所有具有userId
of1
和handleName
of的对象John Doe
。请注意,对象可以具有相同的句柄名称,但可以具有不同的用户ID。这就是为什么我需要将其与第userId
一个匹配。
例如,我想将句柄名称更改为 Donald Stark
我想要这样的结果:
{
"_id": <OBJECT_ID>,
"orders": [
{
"userId": 1,
"handleName": "Donald Stark",
"orderAmount": 3,
"others": [
{
"userId": 1,
"handleName": "Donald Stark"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 2,
"handleName": "Maria Gigante",
"orderAmount": 2,
"others": [
{
"userId": 1,
"handleName": "Donald Stark"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 1,
"handleName": "Donald Stark",
"orderAmount": 4,
"others": [
{
"userId": 1,
"handleName": "Donald Stark"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
},
{
"userId": 3,
"handleName": "John Doe",
"orderAmount": 4,
"others": [
{
"userId": 1,
"handleName": "Donald Stark"
},
{
"userId": 2,
"handleName": "Maria Gigante"
}
]
}
]
}
如何实现的?
更新:我忘了我也有另一个内部数组,我也想更新。
我们可以使用$ [identifier]运算符来更新数组中的特定对象
因此您的更新查询应类似于
db.collection.updateOne(
{ _id: <OBJECT_ID> }, // filter part, add the real objectId here
{ $set: { 'orders.$[order].handleName': 'Donald Stark' } }, // update part
{ arrayFilters: [{ 'order.userId': 1, 'order.handleName': 'John Doe' }]
})
$ [order]仅更新与数组过滤器中的条件匹配的对象
如果您有一个内部数组,并且需要对该内部数组中的元素执行相同的操作,则可以使用类似的方法
db.collection.updateOne(
{ _id: <OBJECT_ID> }, // filter part, add the real objectId here
{ $set: {
'orders.$[order].handleName': 'Donald Stark', // to set the handleName in the elements of the outer array
'orders.$[].others.$[other].handleName': 'Donald Stark' // to set the handleName in the elements of the inner array
} },
{ arrayFilters: [{ 'order.userId': 1, 'order.handleName': 'John Doe' }, { 'other.userId': 1, 'other.handleName': 'John Doe' }] }
)
我们过去$[]
遍历了orders数组中的所有元素,然后$[other]
根据数组过滤器中的新条件用于更新内部数组中的特定元素
希望能帮助到你
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句