For Example, Documents.
[
{
"username": "joy",
"size_info": [
{
"size": "M",
"width": 100,
"height": 102
},
{
"size": "M",
"width": 102,
"height": 104
},
{
"size": "S",
"width": 80,
"height": 82
}
]
}
]
I want to group size_info.size and push array the width and height.
I am trying to create an aggregation. For example for the given documents above, I would look like below:
[
{
"username": "joy",
"size_info": [
{
"size": "M",
"actual_size": [
{
"width": 100,
"height": 102
},
{
"width": 102,
"height": 104
}
]
},
{
"size": "S",
"actual_size": [
{
"width": 80,
"height": 82
}
]
}
]
}
]
Is it possible? thank you for helping
CodePudding user response:
$unwind
- Deconstructsize_info
array into multiple documents.$group
- Group byusername
andsize_info.size
. Add the documents intoactual_size
array.$group
- Group byusername
. Add the documents intosize_info
array.$project
- Decorate the output documents.
db.collection.aggregate([
{
$unwind: "$size_info"
},
{
$group: {
_id: {
username: "$username",
size: "$size_info.size"
},
actual_size: {
$push: {
width: "$size_info.width",
height: "$size_info.height"
}
}
}
},
{
$group: {
_id: "$_id.username",
size_info: {
$push: {
size: "$_id.size",
actual_size: "$actual_size"
}
}
}
},
{
$project: {
_id: 0,
username: "$_id",
size_info: 1
}
}
])