MongoDB 递归查找查询

MongoDB recusrive lookup query

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

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

我想递归地找到给定 Person 的朋友总数,例如

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

这可以使用聚合框架吗?

如果你用的是mongo 3.4+,你可以做$graphLookup,就是在self上做hierarchical join collection

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"]}}}] }}}
])

collection

> 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" ] }