Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to query in a nested array and project only the matching items from array?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading