我有一个集合"people"格式为:
{ "_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"}
]
(数组顺序不重要)。
任何帮助都将非常感激!
- 只需将startWith从
parentID
更改为_id
,这将返回ancestors
与当前文档 $project
显示必填字段
result = 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']