Skip to content

Instantly share code, notes, and snippets.

@drlongnecker
Last active August 29, 2015 13:56
Show Gist options
  • Save drlongnecker/9258985 to your computer and use it in GitHub Desktop.
Save drlongnecker/9258985 to your computer and use it in GitHub Desktop.
Counting child documents by full date in MongoDB
// grab article.comments, group by date (roll times up to full days), count up instances to get full counts per day.
// gotta be a better way...
db.Article.aggregate(
{$unwind: '$Comments'},
{$group: { _id: '$Comments.DateCreated', count : {$sum: 1 }}},
{$match: { '_id' : { $gte: ISODate('2014-02-21 00:00:00'), $lte: ISODate('2014-02-28 23:59:59') } }},
{$project: { _id: 0, count: 1, 'date': '$_id', h: { $hour: '$_id' }, m: { $minute: '$_id'}, s: { $second: '$_id' }, ml: {$millisecond: '$_id'} } },
{$project: { count: 1, 'dt': { "$subtract" : [ "$date", { "$add" : [ "$ml", { "$multiply" : [ "$s", 1000 ] }, { "$multiply" : [ "$m", 60, 1000 ] }, { "$multiply" : [ "$h", 60, 60, 1000 ] } ] } ] } }},
{$group: { _id: '$dt', count: { $sum: '$count' } } },
{$sort: { _id: 1 } }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment