MongoDB monthly count empty months

The name of the picture


MongoDB monthly count empty months



I need to get count for all my orders. What I've done so far is getting count for all months in which there are orders, I need to get all months and if there are no orders count should be 0. How can I achieve that.


database.collection('orders').aggregate([
{"$match": {"state": "finished"}},
{
"$project": {
"y": {
"$year": "$order_date"
},
"m": {
"$month": "$order_date"
}
}
},
{
"$group": {
"_id": {
"month": "$m",
"year": "$y"
},
count: {
"$sum": 1
}
}
}])



This produces following output:


[
{
"_id": {
"month": 9,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 8,
"year": 2017
},
"count": 4
},
{
"_id": {
"month": 11,
"year": 2017
},
"count": 4
},
{
"_id": {
"month": 10,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 4,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 6,
"year": 2017
},
"count": 1
},
{
"_id": {
"month": 3,
"year": 2017
},
"count": 9
},
{
"_id": {
"month": 7,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 2,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 12,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 1,
"year": 2017
},
"count": 2
}
]



There is no results for May so I need to get count 0 for May.





stackoverflow.com/questions/43831891/…
– Hardik Shah
6 hours ago





Hi..can you share with us, the sample Mongo document?
– Subhashree Pradhan
5 hours ago





@SubhashreePradhan dropbox.com/s/8ct2xd7dw9md87t/data.json?dl=0
– priorman
5 hours ago









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP