MongoDB recusrive查询查询

时间:2018-02-09 22:52:51

标签: mongodb mongodb-query aggregation-framework tree-structure

我在MongoDB中有一个文档列表,其结构如下:

{
  'name': 'A',
  'friends': ['B', 'C']
},
{
  'name': 'B',
  'friends': ['A']
},
{
  'name': 'C',
  'friends': ['A']
},
{
  'name': 'D',
  'friends': []
},
{
  'name': 'E',
  'friends': ['C']
}

我想以递归方式找到给定人物的朋友总数,例如

A的朋友:['B', 'C', 'E']

这是否可以使用聚合框架?

1 个答案:

答案 0 :(得分:2)

如果您使用的是mongo 3.4+,则可以$graphLookup,它可以在自我集合中进行分层连接

db.frnds.aggregate([
    {$match : {'name': 'A'}},
    {
       $graphLookup: {
          from: "frnds",
          startWith: "$name",
          connectFromField: "name",
          connectToField: "friends",
          as: "friends"
       }
    },
    {$addFields : { friends : {$setUnion : [{$filter : {input : "$friends.name", as : "friend" , cond : {$ne : ["$name", "$$friend"]}}}] }}}
])

集合

> db.frnds.find()
{ "_id" : ObjectId("5a7e694580aae386f73cf0f5"), "name" : "A", "friends" : [ "B", "C" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f6"), "name" : "B", "friends" : [ "A" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f7"), "name" : "C", "friends" : [ "A" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f8"), "name" : "D", "friends" : [ ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f9"), "name" : "E", "friends" : [ "C" ] }

结果

{ "_id" : ObjectId("5a7e694580aae386f73cf0f5"), "name" : "A", "friends" : [ "B", "C", "E" ] }
相关问题