如何用MongoDBrecursion查询树结构?

例如一个树形结构如;

[ {id: 1 , childrenIdList: [2, 3]}, {id: 2 , childrenIdList: [4, 5]}, {id: 3 , childrenIdList: []}, {id: 4 , childrenIdList: [6, 7]}, {id: 5 , childrenIdList: []}, {id: 6 , childrenIdList: []}, {id: 7 , childrenIdList: []} ] 

这就像

  1 2 3 4 5 6 7 

我如何追踪树从开始叶节点(id = 7)到根(id = 1)?

findid=7的父母很容易;

 db.document.find({childrenList: { $in: [7]}}, {id: 1}).toArray(function(err), result{ /*result gives {"id" : NumberInt(4)} now I should look the parent of id=4, and parent of id=2 as you know. */ }) 

mongodb上的recursion查询是否可能? 我怎样才能实现它?

根据您的使用情况, MongoDB v3.4提供了一个称为$ graphLookup的聚合pipe道运算符。 聚合运算符能够对集合执行recursionsearch。 查看$ graphLookup定义的更多定义 。

使用上面的文档层次结构和值作为示例,您可以尝试在聚合下运行:

 db.collectionName.aggregate([ {$unwind:{ path:"$childrenIdList", preserveNullAndEmptyArrays: true} }, {$graphLookup:{ from:"collectionName", startWith:"$_id", connectFromField:"_id", connectToField:"childrenIdList", as:"myparents", restrictSearchWithMatch: {"_id"}} }, {$match: {"_id": 7 } }, {$group:{ _id:"$_id", parents:{$addToSet:"$myparents._id"} }} ]); 

以上应该返回结果如下:

 { "_id" : 7, "parents" : [ [ 1, 2, 4 ] ] } 

话虽如此,如果你有一个大的集合,上面的查询可能无法执行,因为您将在每个文档上执行$ unwind ,并且将无法使用索引。 正如其他人所build议的,您应该重新考虑您的文档模型结构。 请参阅数据模型树结构 。 根据您的应用程序逻辑和查询用例进行优化,并让灵活的文档架构遵循。

recursion查询是不可能的,你将不得不编码来在代码中recursion调用find 。 或者,您可以重新devise您的架构来保存子代中的父代ID,或者将所有祖代保存为数组或物化path。

请参阅MongoDB已经提供的树形结构数据文档 。