我在模式中的根级别有一个字段,并希望将其添加到数组中匹配条件的每个对象中。
这是一个示例文档...
{
calls: [
{
"name": "sam",
"status": "scheduled"
},
{
"name": "tom",
"status": "cancelled"
},
{
"name": "bob",
"status": "scheduled"
},
],
"time": 1620095400000.0,
"call_id": "ABCABCABC"
}所需文件如下:
[
{
"call_id": "ABCABCABC",
"calls": [
{
"call_id": "ABCABCABC",
"name": "sam",
"status": "scheduled"
},
{
"name": "tom",
"status": "cancelled"
},
{
"call_id": "ABCABCABC",
"name": "bob",
"status": "scheduled"
}
],
"time": 1.6200954e+12
}
]call_id应该添加到数组中所有状态为"scheduled“的对象中。使用mongo聚合可以做到这一点吗?我已经尝试过$addFields,但无法达到上述效果。提前感谢!
发布于 2021-05-04 21:15:54
下面是我如何使用$map和$mergeObjects来做这件事
db.collection.aggregate([
{
"$addFields": {
calls: {
$map: {
input: "$calls",
as: "call",
in: {
$cond: [
{
$eq: [
"$$call.status",
"scheduled"
]
},
{
"$mergeObjects": [
"$$call",
{
call_id: "$call_id"
}
]
},
"$$call"
]
}
}
}
}
}
])https://stackoverflow.com/questions/67385238
复制相似问题