我的收藏采用以下格式,
{
"_id" : ObjectId("5d01fddd3f21c407582e578d"),
"device_name" : "Test Alarm Device",
"description" : "test",
"parameters" : [
{
"parameter_name" : "CO2",
"status" : "on"
},
{
"parameter_name" : "NO",
"status" : "on"
},
{
"parameter_name" : "O2",
"status" : "on"
}
}
现在,我想覆盖(更新)"parameter_name" : "O2"
处的完整对象。
例如,在新集合中,它看起来像...
{
"parameter_name" : "O2",
"status" : "on",
"is_active": true,
"min": 5
}
答案 0 :(得分:1)
使用$out替换现有集合,使用$addFields覆盖现有数组,并使用$map用$cond根据某些条件更新元素。要基于现有对象构建新对象,可以使用$mergeObjects,请尝试:
db.collection.aggregate([
{
$addFields: {
parameters: {
$map: {
input: "$parameters",
in: {
$cond: [
{ "$eq": [ "$$this.parameter_name", "O2" ] },
{ $mergeObjects: [ "$$this", { "is_active": true, "min": 5 } ] },
"$$this"
]
}
}
}
}
},
{ $out: "collection" }
])
答案 1 :(得分:0)
这可以,但是我认为这不是最好的解决方案:
db.collection.updateOne({
_id: ObjectId("5d01fddd3f21c407582e578d"),
{ $set: { "parameters" : [
{
"parameter_name" : "CO2",
"status" : "on"
},
{
"parameter_name" : "NO",
"status" : "on"
},
{
"parameter_name" : "O2",
"status" : "on",
"is_active": true,
"min": 5
}
]
}
}
)