Mongodb子文档字段联合

时间:2018-03-15 08:49:58

标签: mongodb mongodb-query aggregation-framework

我需要加入mongodb的两个集合。首先,我有一个像这样的聚合:

db.messages.aggregate([
{
 $lookup: {
        from :"channels",
        localField: "channels",
        foreignField: "_id",
        as: "merged_channels"
 }
}
]).pretty()
在这种恶化之后,我的文件看起来像这样:

{
    "_id" : "21ca6117-1f14-4613-9407-db7f3a011142",
    "author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
    "title" : "test2",
    "body" : "test2",
    "channels" : [
        "8008d5a8-eb3b-4e55-98c5-a60fd7275bd2",
        "8008d5a8-eb3b-4e55-98c5-a60fd7275bd3"
    ],
    "comments" : [
        {
            "author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
            "body" : "comment1",
            "created_at" : ISODate("2018-03-15T07:08:10.018Z")
        },
        {
            "author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
            "body" : "testbody",
            "created_at" : ISODate("2018-03-15T07:08:09.366Z")
        }
    ],
    "created_at" : ISODate("2018-03-15T07:08:09.018Z"),
    "updated_at" : ISODate("2018-03-15T07:08:09.366Z"),
    "deleted_at" : null,
    "merged_channels" : [
        {
            "_id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275bd2",
            "author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
            "name" : "chan2",
            "members" : [
                {
                    "id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb5",
                    "type" : "group"
                }
            ],
            "created_at" : ISODate("2018-03-15T07:08:08.872Z"),
            "updated_at" : ISODate("2018-03-15T07:08:08.872Z"),
            "deleted_at" : null
        },
        {
            "_id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275bd3",
            "author" : "8008d5a8-eb3b-4e55-98c5-a60fd7275fg4",
            "name" : "chan3",
            "members" : [
                {
                    "id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb5",
                    "type" : "group"
                },
                {
                    "id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb6",
                    "type" : "user"
                },
                {
                    "id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb7",
                    "type" : "role"
                }
            ],
            "created_at" : ISODate("2018-03-15T07:08:08.872Z"),
            "updated_at" : ISODate("2018-03-15T07:08:09.358Z"),
            "deleted_at" : null
        }
    ]
}

我想从chan2和chan3中获取成员字段,将它们合并并放入根(消息)文档中。然后删除merged_channels字段。删除合并字段不是问题,但不知道如何从子对象中提取字段并合并它们。

我将如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以在3.4中使用以下聚合。

$reduce$concatArrays并排除项目以删除merged_channels字段。

db.col.aggregate({
  "$addFields":{
    "merged_arrays":{
      "$reduce":{
        "input":"$merged_channels",
        "initialValue":[],
        "in":{"$concatArrays":["$$value", "$$this.members"]}
      }
    }
  },
  {"$project":{"merged_channels":0}}
})