Group data by Month in MongoDB

56 views Asked by At

I have following set of data where suppose I have 3 set objects in an array:

    [
       {
          "_id":"6530307c64d30c6248a91808",
          "userId":"6530305964d30c6248a917e5",
          "gameType":"car_race",
          "score":1093,
          "winningPosition":0,
          "winningAmount":0,
          "date":"2023-10-18T19:22:36.628Z",
          "userName":"vis2"
       },
       {
          "_id":"65302f9e64d30c6248a91790",
          "userId":"64cfff11b5eb051e525f6d07",
          "gameType":"car_race",
          "score":608,
          "winningPosition":0,
          "winningAmount":0,
          "date":"2023-10-18T19:18:54.695Z",
          "userName":"vis1"
       },
       {
          "_id":"653030d864d30c6248a9183c",
          "userId":"653030c464d30c6248a91816",
          "gameType":"car_race",
          "score":275,
          "winningPosition":0,
          "winningAmount":0,
          "date":"2023-09-18T19:24:08.754Z",
          "userName":"vis3"
       }
    ]

Here we can see, we have first two records from October month and third record from September month. I want output data to be grouped by month as below:

    [
       {
          "month":"october",
          "data":[
             {
                "_id":"6530307c64d30c6248a91808",
                "userId":"6530305964d30c6248a917e5",
                "gameType":"car_race",
                "score":1093,
                "winningPosition":0,
                "winningAmount":0,
                "date":"2023-10-18T19:22:36.628Z",
                "userName":"vis2"
             },
             {
                "_id":"65302f9e64d30c6248a91790",
                "userId":"64cfff11b5eb051e525f6d07",
                "gameType":"car_race",
                "score":608,
                "winningPosition":0,
                "winningAmount":0,
                "date":"2023-10-18T19:18:54.695Z",
                "userName":"vis1"
             }
          ]
       },
       {
          "month":"september",
          "data":[
             {
                "_id":"653030d864d30c6248a9183c",
                "userId":"653030c464d30c6248a91816",
                "gameType":"car_race",
                "score":275,
                "winningPosition":0,
                "winningAmount":0,
                "date":"2023-09-18T19:24:08.754Z",
                "userName":"vis3"
             }
          ]
       }
    ]

Thanks in advance. Please let me know what mongodb query I should write.

0

There are 0 answers