1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This works like a charm. I was wondering, is it possible to only show the employee names in the result?
Yeah, here is the updated example: mongoplayground.net/p/I6qxaSjA3cg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.