gpt4 book ai didi

javascript - 蒙戈 : merge subdocuments and reference the parent in a field

转载 作者:行者123 更新时间:2023-12-01 03:29:14 28 4
gpt4 key购买 nike

我有以下 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com