Maxja
Maxja

Reputation: 545

How to match aggregated ($graphLookup) elements in MongoDB?

Let's say we have:

{ "_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 }

After apply:

db.employees.aggregate([
    {$match: { final: true }},
    {$graphLookup: {
        ...
        as: "reportingHierarchy"
    }}
])

How to filter results by matching properties presented in hierarchy objects reportingHierarchy.[].name. For example will contain Andrew and Eliot at the same time.

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

Upvotes: 0

Views: 874

Answers (2)

Maxja
Maxja

Reputation: 545

I found proper solution for my case is using this:

{$match: 
  {$and: [
    {"reportingHierarchy.name": {$regex: 'And'}}, 
    {"reportingHierarchy.name": {$regex: 'El'}}
  ]}
}

Upvotes: 0

mickl
mickl

Reputation: 49945

reportingHierarchy is a regular array of objects here so you can add next $match stage to your aggregation

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

Upvotes: 3

Related Questions