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

时间:2018-04-29 01:28:47

标签: mongodb recursion aggregate spring-data-mongodb

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

帖子收藏:

{ 
    "_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" : [

    ]`
}

有没有办法可以实现我期待的聚合类型?

由于 Davinder

1 个答案:

答案 0 :(得分:0)

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