MongoDB - 基于嵌套数组的字段值更新数组对象中的字段
Posted
技术标签:
【中文标题】MongoDB - 基于嵌套数组的字段值更新数组对象中的字段【英文标题】:MongoDB - Update field in an array object based on nested array's field value 【发布时间】:2020-05-08 20:04:59 【问题描述】:我正在尝试更新对象数组中的字段,其中嵌套数组中的字段等于一个值。
我的目标是给picture
字段设置一个新的url,其中valueList
中的value
字段是oldRed
产品架构:
variations: [
id: 1,
picture: 'https://example.picture.com',
valueList: [
name: 'color',
value: 'oldRed'
,
name: 'size',
value: 'M'
]
,
id: 2,
picture: 'https://example.picture.com',
valueList: [
name: 'color',
value: 'black'
,
name: 'size',
value: 'M'
]
]
我得到的最接近的是感谢answer,我在其中更新了所有包含 :'oldRed' 的嵌套数组字段。但我的最终目标是根据嵌套数组字段更新其他字段picture
。
db.Product.findOneAndUpdate(
_id: '123'
,
$set:
'variations.$[].valueList.$[nameField].value': 'newRed'
,
arrayFilters: [
'nameField.value': 'oldRed'
],
new: true
);
【问题讨论】:
【参考方案1】:请试试这个:
db.Product.findOneAndUpdate(
_id: 123 ,
$set:
'variations.$[item].valueList.$[nameField].value': 'newRed',
'variations.$[item].picture': 'newURL' // item is each object in variations which is being checked in arrayFilters.
,
arrayFilters: [ 'item.valueList.value': 'oldRed' , 'nameField.value': 'oldRed' ],
new: true
)
收集数据:
"_id" : 123,
"variations" : [
"id" : 1,
"picture" : "https://example.picture.com",
"valueList" : [
"name" : "color",
"value" : "oldRed"
,
"name" : "size",
"value" : "M"
,
"name" : "color",
"value" : "oldRed"
]
,
"id" : 2,
"picture" : "https://example.picture.com",
"valueList" : [
"name" : "color",
"value" : "black"
,
"name" : "size",
"value" : "M"
]
,
"id" : 3,
"picture" : "https://example3.picture.com",
"valueList" : [
"name" : "color",
"value" : "oldRed"
,
"name" : "size",
"value" : "M"
]
]
结果:
/* 1 */
"_id" : 123,
"variations" : [
"id" : 1,
"picture" : "newURL",
"valueList" : [
"name" : "color",
"value" : "newRed"
,
"name" : "size",
"value" : "M"
,
"name" : "color",
"value" : "newRed"
]
,
"id" : 2,
"picture" : "https://example.picture.com",
"valueList" : [
"name" : "color",
"value" : "black"
,
"name" : "size",
"value" : "M"
]
,
"id" : 3,
"picture" : "newURL",
"valueList" : [
"name" : "color",
"value" : "newRed"
,
"name" : "size",
"value" : "M"
]
]
【讨论】:
我认为在 mongoose 中返回更新的文档将是new: true
,如果使用 mongodb 驱动程序或 shell 尝试 returnNewDocument: true
..以上是关于MongoDB - 基于嵌套数组的字段值更新数组对象中的字段的主要内容,如果未能解决你的问题,请参考以下文章