I have assigned person, status inside my collection simply like below
[
{"ASSIGN_ID": "583f84bce58725f76b322398", "STATUS": 1},
{"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 4},
{"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 4},
{"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 3},
{"ASSIGN_ID": "583f84bce58725f76b322311","STATUS": 1},
{"ASSIGN_ID": "583f84bce58725f76b322311","STATUS": 3},
{"ASSIGN_ID": "583f84bce58725f76b322322","STATUS": 1},
{"ASSIGN_ID": "583f84bce58725f76b322322","STATUS": 4}
]
i want to group this data by ASSIGN_ID and inside that by STATUS count of each STATUS same as below.
[
{
"ASSIGN_ID":"583f84bce58725f76b322398",
"STATUS_GROUP":[
{
"STATUS":1,
"COUNT":1
},
{
"STATUS":3,
"COUNT":1
},
{
"STATUS":4,
"COUNT":2
}
]
},
{
"ASSIGN_ID":"583f84bce58725f76b322311",
"STATUS_GROUP":[
{
"STATUS":1,
"COUNT":1
},
{
"STATUS":3,
"COUNT":1
}
]
},
{
"ASSIGN_ID":"583f84bce58725f76b322322",
"STATUS_GROUP":[
{
"STATUS":1,
"COUNT":1
},
{
"STATUS":4,
"COUNT":1
}
]
}
]
however, i have write code and it only grouped by STATUS only. please find the query below.
Inspection.aggregate([
{$group: {
"_id": '$STATUS',
"count" : { $sum : 1 }}}], function (err, result) {
}});
please help me to fix this.
Use this command, it'll work for your sample case, hope it'll fix your problem ,
db.testCollection.aggregate([{
$group: {
_id: {
ASSIGN_ID: "$ASSIGN_ID",
STATUS: "$STATUS"
},
count: {
"$sum": 1
}
}
}, {
$group: {
_id: "$_id.ASSIGN_ID",
STATUS_GROUP: {
$push: {
STATUS: "$_id.STATUS",
count: "$count"
}
}
}
}])
output in shell :
{
"_id": "583f84bce58725f76b322398",
"STATUS_GROUP": [{
"STATUS": 3,
"count": 1
}, {
"STATUS": 4,
"count": 2
}, {
"STATUS": 1,
"count": 1
}]
}, {
"_id": "583f84bce58725f76b322311",
"STATUS_GROUP": [{
"STATUS": 3,
"count": 1
}, {
"STATUS": 1,
"count": 1
}]
}, {
"_id": "583f84bce58725f76b322322",
"STATUS_GROUP": [{
"STATUS": 1,
"count": 1
}, {
"STATUS": 4,
"count": 1
}]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With