Reputation: 1792
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"}]
},
]
Upvotes: 0
Views: 27
Reputation: 8695
Query
$owner
, and $push
pet/pet_name
_id
to owner
and remove the _id
aggregate(
[{"$group":
{"_id": "$owner",
"animals": {"$push": {"pet": "$pet", "pet_name": "$pet_name"}}}},
{"$set": {"owner": "$_id", "_id": "$$REMOVE"}}])
Upvotes: 1