簡體   English   中英

Mongo:合並子文檔並在字段中引用父級

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM