I have a document that I want to group by some specific fields, and for the remaining fields that are not included in the groupby, I want to include them in an embedded array.
An example, let's say that I have the following data
[
{"owner": "A", "pet": "dog", "pet_name": "wouf"},
{"owner": "A", "pet": "cat", "pet_name": "miaou"},
{"owner": "B", "pet": "dog", "pet_name": "wouf_wouf"},
]
I want to group this data by the field owner
and the remaining fields pet
and pet_name
, I want to group them in an array named animals
.
Expected result:
[
{
"owner": "A",
"animals": [
{"pet": "dog", "pet_name": "wouf"},
{"pet": "cat", "pet_name": "miaou"},
],
},
{
"owner": "B",
"animals": [{"pet": "dog", "pet_name": "wouf_wouf"}]
},
]
CodePudding user response:
Query
- group by
$owner
, and$push
- we dont have an operator to remove a field from a document(remove the owner), so a literal document is used, to keep only the
pet/pet_name
- finally rename
_id
toowner
and remove the_id
aggregate(
[{"$group":
{"_id": "$owner",
"animals": {"$push": {"pet": "$pet", "pet_name": "$pet_name"}}}},
{"$set": {"owner": "$_id", "_id": "$$REMOVE"}}])