David Faizulaev
David Faizulaev

Reputation: 5761

MongoDB query to retrieve all matching ids from array

I would like to retrieve documents from the DB that match a manager Id and employee ids which comes in an array.

SELECT * FROM XXX WHERE MANAGER_ID=<manager_id> AND EMPLOYEE_ID IN [....]

Here my code:

var query = [
    {             
        "$and": [ 
            {"employee": { $in : employees}}, 
            {"manager": ObjectId(managerId)}
        ]
    }
];

But in actuality, the query returns all documents in the model. Please advise.

Upvotes: 1

Views: 798

Answers (2)

Ashh
Ashh

Reputation: 46481

In find query first parameter should be an object not an array

var query = {
  "$and": [
    { "employee": { $in : employees }},
    { "manager": ObjectId(managerId) }
  ]
}

db.collection.find(query)

Upvotes: 2

Janen R
Janen R

Reputation: 749

use elemMatch to get matching the array's one or more keys

   ArrayFieldName: {
                "$elemMatch": {
                    "employee": {
                        $in: employees
                    },
                    "manager": ObjectId(managerId)
                }
     }

Upvotes: 0

Related Questions