3

我在 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']

这可能使用聚合框架吗?

4

1 回答 1

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" ] }
于 2018-02-10T03:53:09.413 回答