[英]Mongo: merge subdocuments and reference the parent in a field
我有以下mongo集合:
{
"_id" : ObjectId("000000000001"),
"username" : "user1",
"password" : "password",
"alerts" : [
{
"_id" : ObjectId("5947a8d3b5ac80946b7ee4bd"),
"direction" : "rise",
"threshold" : "1000",
"notified" : true,
"notified_when" : null
},
{
"_id" : ObjectId("5947a8d8b5ac80946b7ee4be"),
"direction" : "rise",
"threshold" : "1200",
"notified" : false,
"notified_when" : null
}
]
},
{
"_id" : ObjectId("000000000002"),
"username" : "user2",
"password" : "password",
"alerts" : [
{
"_id" : ObjectId("5947a8d3b5ac80946b7ee4bd"),
"direction" : "rise",
"threshold" : "1000",
"notified" : true,
"notified_when" : null
}
]
},
{
"_id" : ObjectId("000000000003"),
"username" : "user3",
"password" : "password",
"alerts" : []
}
我只想选择alerts
对象,然后将它们合并在一起。 如果可能的话,我想将父用户的_id
字段注入每个alert
。
我可以用普通的javascript做到这一点,但我想知道MongoDB是否可行。
结果将是:
[
{
"_id" : ObjectId("5947a8d3b5ac80946b7ee4bd"),
"direction" : "rise",
"threshold" : "1000",
"notified" : true,
"notified_when" : null,
"parent_id": ObjectId("000000000001")
},
{
"_id" : ObjectId("5947a8d8b5ac80946b7ee4be"),
"direction" : "rise",
"threshold" : "1200",
"notified" : false,
"notified_when" : null,
"parent_id": ObjectId("000000000001")
},
{
"_id" : ObjectId("5947a8d3b5ac80946b7ee4bd"),
"direction" : "rise",
"threshold" : "1000",
"notified" : true,
"notified_when" : null,
"parent_id": ObjectId("000000000002")
}
]
提前致谢
您可以使用聚合来实现。 首先展开警报数组,然后投影必填字段。 展开解构数组,并为每个数组元素返回一个文档。
db.collection.aggregate(
{$unwind: '$alerts'},
{$project: {
"_id" : '$alerts._id',
"direction" : "$alerts.direction",
"threshold" : "$alerts.threshold",
"notified" : '$alerts.notified',
"notified_when" : '$alerts.notified_when',
"parent_id": '$_id'
}}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.