我有一个收集“人物”的形式:
{ "_id" : 1, "name" : "Grandma"}
{ "_id" : 2, "name" : "Mum", "parentID": "1"}
{ "_id" : 3, "name" : "Uncle", "parentID": "1"}
{ "_id" : 4, "name" : "Kid", "parentID": "2"}
{ "_id" : 5, "name" : "Sister", "parentID": "2"}要获得某个人的祖先(比如Kid),我可以使用简单的match和graphLookup,如下所示:
people.aggregate([
{$match: {_id: "3"}},
{$graphLookup:
{
from: "people",
startWith: "$parentID",
connectFromField: "parentID",
connectToField: "_id",
as: "ancestors"
}
}
])会回来的
{ "_id" : 3, "name" : "Kid", "parentID": "2", "ancestors": [
{ "_id" : 1, "name" : "Grandma"},
{ "_id" : 2, "name" : "Mum", "parentID": "1"}]
}我被困住的地方是如何将输出数据重构为一个单层数组,这样:
array = [
{ "_id" : 1, "name" : "Grandma"},
{ "_id" : 2, "name" : "Mum", "parentID": "1"},
{ "_id" : 3, "name" : "Kid", "parentID": "2"}
](数组顺序不重要)。
任何帮助都将不胜感激!
发布于 2021-02-17 16:02:03
parentID更改为_id,这将返回带有当前文档的ancestors$projectresult = people.aggregate([
{ $match: { _id: "3" } },
{
$graphLookup: {
from: "collection",
startWith: "$_id",
connectFromField: "parentID",
connectToField: "_id",
as: "ancestors"
}
},
{
$project: {
_id: 0,
ancestors: 1
}
}
])通过以下方式访问数组:
finalResult = result[0]['ancestors']https://stackoverflow.com/questions/66242574
复制相似问题