0

I have a collection that's setup like this:

{
   _id: uuid.v4(),
   startDate: Date(),
}

I don't have any ideas for this. The end result I'm looking for, would be something like this ( total is number of users in date ):

[
  {
    date: "2018-12",
    total: 12
  },
  {
    date: "2019-01",
    total: 32
  },
  {
    date: "2019-02",
    total: 23
  },
  ...
]

Any help would be greatly appreciated. Thank you

prasad_
  • 12,755
  • 2
  • 24
  • 36
idestiny137
  • 3
  • 1
  • 2
  • See these to get an idea: [Aggregation group by date example](https://docs.mongodb.com/manual/reference/operator/aggregation/group/#group-by-day-of-the-year) and [Aggregation date operators](https://docs.mongodb.com/manual/reference/operator/aggregation/#date-expression-operators). – prasad_ Nov 01 '19 at 02:41

1 Answers1

0

Try this query

db.collectionName.aggregate([
    {
        $project:{
             period:{$dateToString:{format:"%Y-%m",date:"$startDate"}}
         }
    },{
        $group:{ _id : {date : "$period"},count:{$sum:1}}
    },
      { $sort : { _id : 1 } }
]);
Mahesh Bhatnagar
  • 1,042
  • 1
  • 7
  • 8