MongoDB 递归查找查询

标签 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']
}

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

A 的 friend :['B', 'C', 'E']

这可以使用聚合框架吗?

最佳答案

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

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

关于MongoDB 递归查找查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48715275/

相关文章:

mongodb - 如何有效地加入 MongoDb 中的 2 个巨大集合?

Mongodb 组然后是子组

mongodb - Mongodb中的聚合查询返回特定字段

用于从嵌套数组集合中检索的 mongoDB 查询

python - MongoDB - 如何将 ObjectId 和日期时间显示为字符串(使用 bson.json_util)

javascript - mongoosejs 如何对不同的查询进行排序?

mongodb - 与托管Mongodb进行Grails集成测试

mongodb - $查找结果中的 $match

mongodb - 何时在 mongodb cxx r3.0.2 驱动程序中使用 finalize

mongodb - 将 ISO 日期转换为 yyyy-mm-dd 格式