I have a collection in this format:
{
"place":"land",
"animal":"Tiger",
"name":"xxx"
},
{
"place":"land",
"animal":"Lion",
"name":"yyy"
}
I want to result to be something like this:
{
"place":"land".
"animals":{"Lion":"yyy", "Tiger":"xxx"}
}
I wrote the below query. I think there needs to be another group stage but not able to write it.
db.collection.aggregate({
'$group': {
'_id':{'place':'$place', 'animal':'$animal'},
'animalNames': {'$addToSet':'$name'}
}
})
What changes need to be made to get the required result?
2
Answers
$group
– Group byanimals
. Push objects with{ k: "animal", v: "name" }
type intoanimals
array.$project
– Decorate output document. Convertanimals
array to key-value pair via$arrayToObject
.Sample Mongo Playground
If you are on version >=4.4, a reasonable alternative is to use the
$function
operator: