I have a complex document structure stored in my mongoDB database and I need to extract specific sub-objects from it.
For example:
{
"organization": "Tech Inc",
"CEO": "Alice Johnson",
"departments": [
{
"name": "Engineering"
"head": "Bob Smith"
"employees": [
{
"name": "Sarah"
"position": "Software Developer"
},
// ... many more employees
]
},
// ... many more departments
]
}
MongoDB recently introduced the ability to retrieve 1-level-deep sub-objects using $elemMatch projection:
var projection = { _id: 0, departments: { $elemMatch: { name: "Engineering" } } };
db.organizations.find({"organization": "Tech Inc"}, projection);
// returns { "departments": [ /* array containing only the matching department */ ] }
However, attempting to fetch a sub-object at a deeper level (e.g., retrieving a specific employee) using the same method results in an error:
var projection = { _id: 0, "departments.employees": { $elemMatch: { name: "Sarah" } } };
db.organizations.find({"organization": "Tech Inc"}, projection);
// "$err": "Cannot use $elemMatch projection on a nested field (currently unsupported).", "code": 16344
Is there a workaround for retrieving arbitrarily deep sub-objects within a MongoDB document?
I am currently using MongoDB version 2.2.1