Skip to content

Instantly share code, notes, and snippets.

@rantav
Created August 31, 2012 11:07
Show Gist options
  • Save rantav/3551498 to your computer and use it in GitHub Desktop.
Save rantav/3551498 to your computer and use it in GitHub Desktop.
// Old style mongodb group and a bit more of javascript to complete the task (Array.sort and Array.slice)
db.Session.group({
key: {user: true},
cond: {
serviceId: '888',
end: {$gte: ISODate('2012-08-30T00:00:00Z'), $lte: ISODate('2012-08-31T00:00:00Z')},
start: {$lte: ISODate('2012-08-31T00:00:00Z')}
},
initial: {durationSeconds: 0},
reduce: function(obj, prev) {prev.durationSeconds += obj.durationSeconds;}
}).sort(function(a, b) { return b.durationSeconds - a.durationSeconds}).slice(10, 15)
// Using the new (mongo 2.2) aggregation framework. Pure server side, no need of extra JS postprocessing.
db.Session.aggregate(
{
$match: {
serviceId: '888',
end: {$gte: ISODate('2012-08-30T00:00:00Z'), $lte: ISODate('2012-08-31T00:00:00Z')},
start: {$lte: ISODate('2012-08-31T00:00:00Z')}
}
},
{
$project: {
user: 1,
durationSeconds: 1
}
},
{
$group: {
_id: '$user',
durationSeconds: {$sum: '$durationSeconds'}
}
},
{
$sort: {
durationSeconds: -1
}
},
{
$skip: 10
},
{
$limit: 5
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment