Skip to content

Instantly share code, notes, and snippets.

@lauris
Created May 14, 2020 09:40
Show Gist options
  • Save lauris/d62d20c38b557718a59cc00c0580d915 to your computer and use it in GitHub Desktop.
Save lauris/d62d20c38b557718a59cc00c0580d915 to your computer and use it in GitHub Desktop.
MongoDB aggregate entries by month
db.getCollection('users').aggregate(
[
{
$group:
{
_id:
{
month: { $month: "$created" },
year: { $year: "$created" }
},
count: { $sum:1 },
date: { $first: "$created" }
}
},
{
$project:
{
date:
{
$dateToString: { format: "%Y-%m", date: "$date" }
},
count: 1,
_id: 0
}
},
{ $sort: {
'date': -1,
}}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment