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:
CodePudding user response:
For the specific case of the first item use:
db.collection.aggregate([
{
$project: {
groupName: {
$first: "$groups.name"
}
}
}
])
See how it works on the playground example
For mongodb version older than 4.2 use:
db.collection.aggregate([
{
$project: {
groupName: {
$arrayElemAt: ["$groups.name", 0]
}
}
}
])
CodePudding user response:
I finally found the right way to query and project the nested array of object as follows:
I had to use $arrayElemAt
as such:
db.getCollection("Comapny").aggregate([
{
$match: {
"companyID": "123456789",
}
},
{
$sort: { _updated_at: -1 }
},
{
$project: {
_id: "$_id",
groups: {$arrayElemAt: [ "$groups.name", 0 ] },
}
}
])