I'm trying to merge objects of an array in the aggregation pipeline. Here is MongoDB Document.
{
"category" : [
{
"id" : ObjectId("60ed3d041436f1310401b1b2"),
"name" : "cat 1",
"services" : [
{
"_id" : ObjectId("607ab64bc520c2587045694b"),
"name" : "service 1",
}
]
}
]
},
{
"category" : [
{
"id" : ObjectId("60ed3cff1436f1310401b1b1"),
"name" : "cat 2",
"services" : [
{
"_id" : ObjectId("5ffd5d4bc4967a1b10bf5022"),
"name" : "service 2",
}
]
},
{
"id" : ObjectId("60ed3cff1436f1310401b1b1"),
"name" : "cat 2",
"services" : [
{
"_id" : ObjectId("6077e777ad481470d42c4e41"),
"name" : "service 3",
}
]
}
]
}
Expected Output
I need to merge the category
array into one and merge the service
array based on the category
[
{
"id" : ObjectId("60ed3d041436f1310401b1b2"),
"name" : "cat 1",
"services" : [
{
"_id" : ObjectId("607ab64bc520c2587045694b"),
"name" : "service 1",
}
]
},
{
"id" : ObjectId("60ed3cff1436f1310401b1b1"),
"name" : "cat 2",
"services" : [
{
"_id" : ObjectId("5ffd5d4bc4967a1b10bf5022"),
"name" : "service 2",
},
{
"_id" : ObjectId("6077e777ad481470d42c4e41"),
"name" : "service 3",
}
]
},
]
How to achieve this ?.
CodePudding user response:
Try this one:
db.collection.aggregate([
{ $unwind: "$category" },
{
$group: {
_id: {
_id: "$_id",
name: "$category.name"
},
services: { $push: { $first: "$category.services" } }
}
},
{
$project: {
_id: "$_id._id",
name: "$_id.name",
services: 1
}
}
])
See Mongo Playground