Skip to content

Instantly share code, notes, and snippets.

@tigreped
Created February 11, 2019 14:05
Show Gist options
  • Select an option

  • Save tigreped/c8241bd0af7642bed702a69206870a8f to your computer and use it in GitHub Desktop.

Select an option

Save tigreped/c8241bd0af7642bed702a69206870a8f to your computer and use it in GitHub Desktop.
// Group by minute:
var format = '%Y-%m-%dT%H:%M';
// The string field for the record's period
var periodField = 'period';
// The field that is used as the average weight
var weightField = 'generated';
// The filter field to be multiplied in the average: $avgSolveTime, $callbacksExecuted, etc
var valueField = 'callbacksExecuted';
// The date field used to group data by minute
var dateField = 'last';
// For a single user
var aggregationOneUser = db.getCollection('statsSerpsAggregatedMinute').aggregate([
{
$match: {
period: { '$gte': '2019-01-01T00:00:00.000Z', '$lte': '2019-02-01T00:00:00.000Z' },
userId: 'VGWBkUCcXAql5bTtP'
}
},
{
$group: {
_id: { $dateToString: { format: format, date: "$last" } },
numerator: { $sum: { $multiply: [ '$'+[weightField], '$'+[valueField] ] } },
denominator: { $sum: '$'+[weightField] }
}
},
{
$project: {
weighedAverage: { $divide: [ "$numerator", "$denominator" ] },
}
},
{
$sort: {_id: 1}
}
]);
aggregationOneUser.forEach(function(item) {
print('* Aggregation: ' + JSON.stringify(item));
});
// For all users
var aggregationAllUsers = db.getCollection('statsSerpsAggregatedMinute').aggregate([
{
$match: {
[periodField]: { '$gte': '2019-01-01T00:00:00.000Z', '$lte': '2019-02-01T00:00:00.000Z' },
}
},
{
$group: {
_id : { $dateToString: { format: format, date: '$'+[dateField] } }, // group by minute
numerator: { $sum: { $multiply: [ '$'+[weightField], '$'+[valueField] ] } },
denominator: { $sum: '$'+[weightField] }
}
},
{
$project: {
weighedAverage: { $divide: [ "$numerator", "$denominator" ] },
}
},
{
$sort: {_id: 1}
}
]);
aggregationAllUsers.forEach(function(item) {
print('* Aggregation: ' + JSON.stringify(item));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment