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

标签 javascript node.js mongodb

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

相关文章:

javascript - 使用 Javascript 清理字符串

Node.js - 获取当前文件名

javascript - Node.js 将响应对象句柄的句柄传递给子进程

javascript - 使用 MEAN 堆栈查询关联模型

javascript - 禁用提交按钮后表单未提交

javascript - 如果 React 组件是一个类,为什么它还要维护一个状态?

python - 从一个虚拟机连接到另一个虚拟机时,python 中的 urlopen 错误 [Errno 111] 连接被拒绝

javascript - 使用集合过滤事件

javascript - CSS 打印内容溢出页脚。如何解决?

javascript - jquery 变量不显示每个循环的值