更改子文档猫鼬的多个对象中的特定字段
Change a specific field in multiple object of a sub document mongoose
我正在尝试将子文档的多个对象中的特定字段更改为 false,但是当我尝试使用 $set
更新文档时遇到猫鼬问题。
这是数据结构。
[{
name: 'Joe',
card: [
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
{ type: 'unionPay', select: true},
]
},{
name: 'Pascal',
card: [
{ type: 'unionPay', select: false},
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
]
}]
执行结果
[{
name: 'Joe',
card: [
{ type: 'visa', select: false}, <--- was changed to false
{ type: 'masterCard', select: false},
{ type: 'unionPay', select: false}, <--- was changed to false
]
},{
name: 'Pascal',
card: [
{ type: 'unionPay', select: false},
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
]
}]
我目前正在编写此查询,但它没有按预期工作。
this.user.model().findOneAndUpdate(
{ name: 'Joe },
{
card:{$set: { select: false },
},
);
我做错了什么?
演示 - https://mongoplayground.net/p/-ScRx2XpZ9E
使用$[]
The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation
一次可以更新1个顶级索引
db.collection.update(
{ name: "Joe" },
{ $set: { "card.$[c].select": false } },
{ arrayFilters: [ { "c.type": "visa" } ] }
)
使用 db.collection.bulkWrite 一次进行 2 次查询。
db.collection.bulkWrite( [
{
updateOne : {
"filter":{ name: "Joe" },
"update": { $set: { "card.$[c].select": false } },
"arrayFilters": [ { "c.type": "visa" } ]
}
},
{
updateOne : {
"filter":{ name: "Joe" },
"update": { $set: { "card.$[c].select": false } },
"arrayFilters": [ { "c.type": "unionPay" } ]
}
}
])
我正在尝试将子文档的多个对象中的特定字段更改为 false,但是当我尝试使用 $set
更新文档时遇到猫鼬问题。
这是数据结构。
[{
name: 'Joe',
card: [
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
{ type: 'unionPay', select: true},
]
},{
name: 'Pascal',
card: [
{ type: 'unionPay', select: false},
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
]
}]
执行结果
[{
name: 'Joe',
card: [
{ type: 'visa', select: false}, <--- was changed to false
{ type: 'masterCard', select: false},
{ type: 'unionPay', select: false}, <--- was changed to false
]
},{
name: 'Pascal',
card: [
{ type: 'unionPay', select: false},
{ type: 'visa', select: true},
{ type: 'masterCard', select: false},
]
}]
我目前正在编写此查询,但它没有按预期工作。
this.user.model().findOneAndUpdate(
{ name: 'Joe },
{
card:{$set: { select: false },
},
);
我做错了什么?
演示 - https://mongoplayground.net/p/-ScRx2XpZ9E
使用$[]
The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation
一次可以更新1个顶级索引
db.collection.update(
{ name: "Joe" },
{ $set: { "card.$[c].select": false } },
{ arrayFilters: [ { "c.type": "visa" } ] }
)
使用 db.collection.bulkWrite 一次进行 2 次查询。
db.collection.bulkWrite( [
{
updateOne : {
"filter":{ name: "Joe" },
"update": { $set: { "card.$[c].select": false } },
"arrayFilters": [ { "c.type": "visa" } ]
}
},
{
updateOne : {
"filter":{ name: "Joe" },
"update": { $set: { "card.$[c].select": false } },
"arrayFilters": [ { "c.type": "unionPay" } ]
}
}
])