Home > Software engineering >  How to query in a nested array and project only the matching items from array?
How to query in a nested array and project only the matching items from array?

Time:12-19

The structure looks like this:

{

    clientName: "client1",
    employees: [
        {
            "employeename": 1,
            "configuration": {
                "isAdmin": true,
                "isManager": false
            }
        }
        {
            "employeename": 2,
            "configuration": {
                "isAdmin": false,
                "isManager": false
            }
        }...
        
    ]
},
{
...
}

` I want to see the employees who are admins inside a specific client, given that, I have the client name. How can I write a query in MongoDB for this? I want to be able to see (project) only employees who match? Can I combine it to match multiple conditions? for example: someone who is an admin and a manager.

I have tried doing:

db.collection.find({clientName: "client1", "employees.configuration.isAdmin": true}, {"employees.employeename": 1})

This just return all the employees.

I've also tried using $elemMatch, to no avail.

Any help is appreciated.

CodePudding user response:

You can do it with Aggregation framework:

  • $match - to filter the document based on clientName property
  • $filter with $eq - to filter only employees that have admins
db.collection.aggregate([
  {
    "$match": {
      "clientName": "client1"
    }
  },
  {
    "$set": {
      "employees": {
        "$filter": {
          "input": "$employees",
          "cond": {
            "$eq": [
              "$$this.configuration.isAdmin",
              true
            ]
          }
        }
      }
    }
  }
])

Working example

  • Related