I have an array of objects in my company collection holding grouped values as follows:
"groups" : [
{
"id" : "d278c44333",
"name" : "group 1"
}
],
so in mongoDB it would be company > groups > 0 > id or name
I want to project all of the documents that have the groups array of objects and retrieve the name.
How can I do that?
Here is what i tried:
db.getCollection("Company").aggregate([
{
$match: {
"companyID": "323452343",
}
},
{
$project: {
//this only projects groupName with an array with 0 elements inside.
groupName: "$groups.0.name"
}
}
])
EDIT:
expected result:
2
Answers
I finally found the right way to query and project the nested array of object as follows:
I had to use
$arrayElemAt
as such:For the specific case of the first item use:
See how it works on the playground example
For mongodb version older than 4.2 use: