To count data based on the condition in the $group stage we can make use of "$accumulator" operator which is changed in MongoDb version 5.0
So based on your requirement we can implement using this aggregation stage -
db.products.aggregate([
{
$group: {
_id: "$item",
totalCounts: { $sum: 1 },
countsMeta: {
$accumulator: {
init: function () {
// Set the initial state
return { countSmaller: 0, countBigger: 0 };
},
accumulate: function (state, value) {
// Define how to update the state
return value < 10
? { ...state, countSmaller: state.countSmaller + 1 }
: { ...state, countBigger: state.countBigger + 1 };
},
accumulateArgs: ["$value"], // Pass the desired argument to the accumulate function
merge: function (state1, state2) {
/*
Executed when the operator performs a merge,
Merge may happen in two cases :
1). $accumulator is run on a sharded cluster. The operator needs to merge the
results from each shard to obtain the final result.
2). A single $accumulator operation exceeds its specified memory limit.
If you specify the allowDiskUse option, the operator stores the
in-progress operation on disk and finishes the operation in memory.
Once the operation finishes, the results from disk and memory are
merged together using the merge function.
The merge function always merges two states at a time. In the event that more
than two states must be merged, the resulting merge of two states is merged
with a single state. This process repeats until all states are merged.
*/
return {
countSmaller: state1.countSmaller + state2.countSmaller,
countBigger: state1.countBigger + state2.countBigger,
};
},
finalize: function (state) {
// After collecting the results from all documents,
return state;
},
lang: "js",
},
},
},
},
]);
This execution gives the following result
For more information about stage and operator refer the following link
https://www.mongodb.com/docs/manual/reference/operator/aggregation/accumulator/
Hope this will help you or somebody else. Thanks!
Happy Coding :-)
value
field is a string, so you may want to convert that key value to a number. – Polestar