我正在使用mongodb将信息存储到数据库中。但是我不知道我将管道用于从中获取数据的同一集合吗?让我用一个例子来解释它:
我在集合“清单”示例中有一些文档:-
{
"_id" : 1,
"review" : "this is a review",
"bot_id" : 1
}
{
"_id" : 2,
"review" : "this is a second review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1
}
{
"_id" : 3,
"review" : "this is a third review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1
}
{
"_id" : 4,
"review" : "this is a another review",
"bot_id" : 2
}
{
"_id" : 5,
"review" : "this is a fifth review",
"type" : "reply",
"reply_to" : 2,
"bot_id" : 1
}
我必须获取结果,例如第一个文档的_id
附加到第二个,第三个文档的reply_to
字段,并且匹配项将位于bot_id
字段,第一个文档就像是父文档,然后第二个和第三个文档将充当第一个文档的子文档,然后使用_id:4
也是父文档。谁能解释得到我想要的输出后我应该执行什么查询?
我想要的输出:-
{
"_id" : 1,
"review" : "this is a review",
"bot_id" : 1
"replies":[
{
"_id" : 2,
"review" : "this is a second review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1,
"replies":[
{
"_id" : 5,
"review" : "this is a fifth review",
"type" : "reply",
"reply_to" : 2,
"bot_id" : 1,
}
]
},
{
"_id" : 3,
"review" : "this is a third review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1
}
]
}
{
"_id" : 4,
"review" : "this is a another review",
"bot_id" : 2
}
答案 0 :(得分:0)
我可以通过使用$graphLookup
聚合,如下所示来为您提供一级 reply_to :
db.collectionName.aggregate([
{
$match: {"reply_to" : null }
},
{
$graphLookup: {
from: "collectionName",
startWith:"$_id" ,
connectFromField: "_id",
connectToField: "reply_to",
as: "replies"
}
}]).pretty()
输出为:
{
"_id" : 1,
"review" : "this is a review",
"bot_id" : 1,
"replies" : [
{
"_id" : 3,
"review" : "this is a third review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1
},
{
"_id" : 5,
"review" : "this is a fifth review",
"type" : "reply",
"reply_to" : 2,
"bot_id" : 1
},
{
"_id" : 2,
"review" : "this is a second review",
"type" : "reply",
"reply_to" : 1,
"bot_id" : 1
}
]
}
{
"_id" : 4,
"review" : "this is a another review",
"bot_id" : 2,
"replies" : [ ]
}
在更高层次上,您已经签出graph lookup的正式文档