0

I wants to get data count by 3 months wise in MongoDB

count by January to March count by March to June count by June to September count by September to December

{
    "_id" : ObjectId("62aecc436b905928c4209e63"),
    "date" : ISODate("2021-06-25T00:00:00.000Z"),
    "order_id" : 1,
    "total": 100
},
{
    "_id" : ObjectId("62aecc436b905928c4209e64"),
    "date" : ISODate("2022-03-20T00:00:00.000Z"),
    "order_id" : 2,
    "total": 200
}
{
    "_id" : ObjectId("62aecc436b905928c4209e65"),
    "date" : ISODate("2022-11-03T00:00:00.000Z"),
    "order_id" : 3,
    "total": 300
}

1 Answers1

1

in version 5.0 try this

 db.data.aggregate(
   [
     {
       $group:
         {
   _id:{ $dateTrunc: { date: "$date", unit: "quarter" } },
    count: { $count: {}}
         }
     }
   ]
)

result

{
    "_id" : ISODate("2021-04-01T07:00:00.000+07:00"),
    "count" : 1
},
{
    "_id" : ISODate("2022-01-01T07:00:00.000+07:00"),
    "count" : 1
},
{
    "_id" : ISODate("2022-10-01T07:00:00.000+07:00"),
    "count" : 1
}

_id is the start date of the quarter.

DayDreamer
  • 116
  • 5