I have a query that aggregates data and produces results mostly as desired. However, I need to group only by branchId (not branchId and name) and organize the "name" values in an object along with their corresponding results.
Here is the schema:
{
process: { type: String, required: true },
name: { type: String, required: true },
error: { type: String },
action: {
type: String,
required: true,
enum: ['started', 'stopped', 'processing', 'completed', 'errored']
},
location: {
branchId: { type: String }
},
},
{ timestamps: true }
This is the current aggregation query:
[
{
$match: {
createdAt: { $gte: ISODate("2020-06-24T00:00:00.000+0000"),
$lte: ISODate("2020-06-25T00:00:00.000+0000")
}
}
},
{
$group: {
_id: { branchId: '$location.branchId', name: '$name' },
started: { $sum: { $cond: [{ $eq: ['$action', 'started'] }, 1, 0] } },
processing: { $sum: { $cond: [{ $eq: ['$action', 'processing'] }, 1, 0] } },
errored: { $sum: { $cond: [{ $eq: ['$action', 'errored'] }, 1, 0] } },
completed: { $sum: { $cond: [{ $eq: ['$action', 'completed'] }, 1, 0] }
}
}
},
]
CURRENT RESPONSE:
{
"_id" : {
"branchId" : "1",
"name" : "Product 1"
},
"started" : 1.0,
"processing" : 1.0,
"errored" : 0.0,
"completed" : 0.0
},
{
"_id" : {
"branchId" : "1",
"name" : "Product 2"
},
"started" : 1.0,
"processing" : 1.0,
"errored" : 1.0,
"completed" : 1.0
}
To achieve the DESIRED RESPONSE similar to the following, how can I modify the query?
{
"_id" : "1",
"product_1": {
"started" : true,
"processing" : true,
"errored" : true,
"completed" : false
},
"product_2": {
"started" : true,
"processing" : true,
"errored" : false,
"completed" : true
}
},
I have set up a playground for testing: https://mongoplayground.net/p/zDaxC-SYtN4