MongoDB query IN array of object MongoDB query IN array of object arrays arrays

MongoDB query IN array of object


This can not be done with a simple query. You will have to loop over employees.departments and for each iteration add its departments_id to an array. This array you then can use in your second line. This is something best done in your language of choice.

In order to make this easier, you'll have to change your schema. One option is tostore the department information in the employee record, but in your case you'd be duplicating a lot of data.

I would instead suggest to have each department contain a list with employee IDs and dates instead like this:

{        "_id" : ObjectId("4f9643957f8b9a3f0a000004"),        "dept_name" : "Marketing",        "managers" : [        ]        "employees" : [            {                    "employee_id" : ObjectId("4f9643967f8b9a3f0a00005a"),                    "from_date" : "1990-01-03",                    "to_date" : "1990-01-15"            }        ]}

In that case, you can then simply run:

db.departments.find( { "employees.employee_id": ObjectId("some_id") } );


There is an easy way to do that in Mongo 3.2, at least in just a single operation:

const employees = db.employees.find(); // query the employees collectiondb.departments.find({  managers: {    $elemMatch: {      employees_id: {        $in: employees.map(e => e._id)      }    }  }});

The $elemMatch modifier (see ref) helps query against an array-like value of an object property.