如何过滤MongoDB中的聚合元素?

时间:2018-02-21 11:32:33

标签: mongodb

在官方mongo文档中,aggregate section中有一个示例说明$graphLookup在每个结果元素中包含reportingHierarchy字段。但是如何过滤某些键中的最终元素集。

{ "_id": 1, "name": "Dev", final: false }
{ "_id": 2, "name": "Eliot", "reportsTo" : "Dev", final: false }
{ "_id": 3, "name": "Ron", "reportsTo" : "Eliot", final: false }
{ "_id": 4, "name": "Andrew", "reportsTo" : "Eliot", final: false }
{ "_id": 5, "name": "Asya", "reportsTo" : "Ron", final: true }
{ "_id": 6, "name": "Dan", "reportsTo" : "Andrew", final: true }

我需要向此查询添加什么,以确定我只对包含final: true param的记录感兴趣,但仍然获取所有reportingHierarchy树?

db.employees.aggregate( [
   ???
   {
      $graphLookup: {
         from: "employees",
         startWith: "$reportsTo",
         connectFromField: "reportsTo",
         connectToField: "name",
         as: "reportingHierarchy"
      }
   }
] )

预期产出:

{ "_id": 5, "name": "Asya", "reportsTo" : "Ron", final: true,
    "reportingHierarchy": [
        { "_id": 1, "name": "Dev", final: false },
        { "_id": 2, "name": "Eliot", "reportsTo" : "Dev", final: false },
        { "_id": 3, "name": "Ron", "reportsTo" : "Eliot", final: false }
    ]
}
{ "_id": 6, "name": "Dan", "reportsTo" : "Andrew", final: true,
    "reportingHierarchy": [
        { "_id": 1, "name": "Dev", final: false },
        { "_id": 2, "name": "Eliot", "reportsTo" : "Dev", final: false },
        { "_id": 4, "name": "Andrew", "reportsTo" : "Eliot", final: false }
    ]
}

2 个答案:

答案 0 :(得分:2)

首先使用$match过滤掉您想要的记录。

db.employees.aggregate([
   { 
       $match: { final: true } 
   },
   {
      $graphLookup: {
         from: "employees",
         startWith: "$reportsTo",
         connectFromField: "reportsTo",
         connectToField: "name",
         as: "reportingHierarchy"
      }
   }
])

答案 1 :(得分:-1)

你可以试试这个,

db.employees.aggregate([{
            $match: {
                    "final": true
            }
        }, {
            $graphLookup: {
                from: "employees",
                startWith: "$reportsTo",
                connectFromField: "reportsTo",
                connectToField: "name",
                as: "reportingHierarchy"
            }
        }, {
            $addFields: {
                reportingHierarchy: {
                    $filter: {
                        input: "$reportingHierarchy",
                        as: "reportingHierarchy_field",
                        cond: {
                            $and: [{
                                    $eq: ["$$reportingHierarchy_field.final", true]
                                }
                            ]
                        }
                    }
                },
            }
        }
    ])