Mongodb 将文档聚合到嵌套层次结构中

Mongodb Aggregated documents into a nested hierarchy

我正在尝试将集合中的文档聚合到嵌套图。以下是我正在使用的评论存储应用程序的示例数据 -

帖子集:

{ 
    "_id" : "1", 
    "text" : "hey", 
}
{ 
    "_id" : "2", 
    "text" : "hello", 
    "replyTo" : "1"
}
{ 
    "_id" : "3", 
    "text" : "What's up?", 
    "replyTo" : "2"
}
{ 
    "_id" : "4", 
    "text" : "How are you", 
    "replyTo" : "1"
}

{ 
    "_id" : "5", 
    "text" : "Knock, knock!", 
}

我期望的结果应该如下所示:

{
   "_id": "1",
   "text": "hey",
   "replies": [
      {
         "_id": "2",
         "text": "hello",
         "replyTo": "1",
         "replies": [
            {
               "_id": "3",
               "text": "What's up?",
               "replyTo": "2"
            }
         ]
      },
      {
         "_id": "4",
         "text": "How are you",
         "replyTo": "1"
      }
   ]
}

{ 
    "_id" : "5", 
    "text" : "Knock, knock!", 
}

我尝试了递归处理文档的 $graphLookup,但结果是一个平面数组,这不是我所期望的 -

db.posts.aggregate(
    [
        { 
            "$graphLookup" : {
                "from" : "posts", 
                "startWith" : "$_id", 
                "connectFromField" : "_id", 
                "connectToField" : "replyTo", 
                "as" : "replies"
            }
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);

结果:

{ 
    "_id" : "1", 
    "text" : "hey", 
    "slug_path" : "1", 
    "replies" : [
        {
            "_id" : "2", 
            "text" : "hello", 
            "slug_path" : "1/2", 
            "replyTo" : "1"
        }, 
        {
            "_id" : "4", 
            "text" : "How are you", 
            "slug_path" : "1/4", 
            "replyTo" : "1"
        }, 
        {
            "_id" : "3", 
            "text" : "what's up?", 
            "slug_path" : "1/2/3", 
            "replyTo" : "2"
        }
    ]
}
{ 
    "_id" : "2", 
    "text" : "hello", 
    "slug_path" : "1/2", 
    "replyTo" : "1", 
    "replies" : [
        {
            "_id" : "3", 
            "text" : "what's up?", 
            "slug_path" : "1/2/3", 
            "replyTo" : "2"
        }
    ]
}
{ 
    "_id" : "4", 
    "text" : "How are you", 
    "slug_path" : "1/4", 
    "replyTo" : "1", 
    "replies" : [

    ]
}
{ 
    "_id" : "3", 
    "text" : "what's up?", 
    "slug_path" : "1/2/3", 
    "replyTo" : "2", 
    "replies" : [

    ]
}
{ 
    "_id" : "5", 
    "text" : "Knock, knock!", 
    "replies" : [

    ]`
}

有什么方法可以实现我期望的聚合类型?

谢谢 达文德

我最终放弃了 $graphLookup,因为它只能给出一级父子关系,并且不能递归地创建树状结构作为结果。我能够在 Java 中完全创建树状结构,并且从性能角度来看程序 运行 很快。