db.COLLECTION.aggregate([
// 1. Filter (optional)
{$match:
{
FIELD_1 : { $in: [ 'VALUE_1', 'VALUE_2' ] }
}
}
// 2. Group number one
, {$group :
{
_id: {
"FIELD_TO_GROUP_BY_1_ALIAS" : "$FIELD_TO_GROUP_BY_1"
, "FIELD_TO_GROUP_BY_2_ALIAS" : "$FIELD_TO_GROUP_BY_2"
}
, AGGREGATION_ALIAS : {$sum : "$FIELD_TO_AGGREGATE"}
}
}// group 1
// 3. Match (filter on the results of the previous aggregation)
, {$match :
{
population: {$gt : NUMERIC_VALUE }
}
}// match
// 4. Group by
, {$group :
{
_id: {"FIELD_TO_GROUP_BY_ALIAS" : "$FIELD_TO_GROUP_BY" }
, AGGREGATION_ALIAS : { $avg : "$FIELD_TO_AGGREGATE" }
}
}// group 2
// 5. Sort descending
, {$sort :
{
FIELD_OR_ALIAS_TO_SORT_BY : -1
}
}//sort
]);
No comments:
Post a Comment