作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下 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
字段注入(inject)到每个 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")
}
]
提前致谢
最佳答案
您可以使用聚合来实现它。第一 unwind警报数组,然后投影所需的字段。 Unwind 解构数组,并为每个数组元素返回一个文档。
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'
}}
)
关于javascript - 蒙戈 : merge subdocuments and reference the parent in a field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632491/
我是一名优秀的程序员,十分优秀!