Below is my sample collection :-
{
"_id" : "fffdb22b-912d-4166-909b-7d0fe790ba2a",
"companyVendorId" : "1001",
"date" : ISODate("2019-01-02T05:30:00.000+05:30"),
"amount" : 100
},
{
"_id" : "fff94874-27af-4a39-ae59-3a46b8c7f573",
"companyVendorId" : "1002",
"date" : ISODate("2019-01-25T05:30:00.000+05:30"),
"amount" : 200
},
{
"_id" : "fff94874-27af-4a39-ae59-3a46b8c7f573",
"companyVendorId" : "1002",
"date" : ISODate("2019-01-29T05:30:00.000+05:30"),
"amount" : 200
},
{
"_id" : "fff68faf-2f11-480f-83d2-bfcb45b12d5b",
"companyVendorId" : "1004",
"date" : ISODate("2019-01-12T05:30:00.000+05:30"),
"amount" : 500
},
{
"_id" : "fff4dfaa-46cd-48e3-a871-1f086a2c5438",
"companyVendorId" : "1005",
"date" : ISODate("2019-02-13T05:30:00.000+05:30"),
"amount" :600
},
{
"_id" : "fff18ff2-015e-4ddc-81f2-a12ab3503d05",
"companyVendorId" : "1006",
"date" : ISODate("2019-02-08T05:30:00.000+05:30"),
"amount" : 700
},
{
"_id" : "ffeb16cd-ae1b-4c1e-aa93-d64347b5ff38",
"companyVendorId" : "1007",
"date" : ISODate("2019-02-18T05:30:00.000+05:30"),
"amount" :800
}
Requirement :- I need top 2 vendors for each month (for current year) based on their amount, if more than one transactions are there for same "companyVendorId" in one month then we need to show sum of amount.
Expected result :-
{
"month":1
"companyVendorId" : "1004",
"totalAmount" : 500
},
{
"month":1
"companyVendorId" : "1002",
"totalAmount" : 400
},
{
"month":2
"companyVendorId" : "1007",
"totalAmount" :800
},
{
"month":2
"companyVendorId" : "1006",
"totalAmount" : 700
}
So far i am in between trying to make query, below query i am able to make :-
db.getCollection('transaction').aggregate([
{
"$project":
{
"amount": 1,
"companyVendorId":1,
"month": { "$month": "$date" }, "year": { "$year": "$date" }
}
},
{
"$match":
{
"year": 2020
}
}, {
"$group": {
"_id": {
"month": "$month",
"companyVendorId":"$companyVendorId"
},
"totalAmount": { "$sum": "$amount" }
}
}
])
This query giving me result based on my requirement but not able to select top 2 vendors.