Created
May 14, 2020 09:40
-
-
Save lauris/d62d20c38b557718a59cc00c0580d915 to your computer and use it in GitHub Desktop.
MongoDB aggregate entries by month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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