ram12393
ram12393

Reputation: 1258

Group by month and date in mongodb and display the list

My DB products schema structure

{ "_id" :  "507d95d5719dbef170f15bf9" , "name" : "AC3 Series Charger", "type" : "accessory", "price" : 19,"created":"1626083461034"}
{ "_id" :  "507d95d5719dbef170f15bfa" , "name" : "AC3 Case Green", "type" : "case" ,  "price" : 12, "created":"1625805979235"}
{ "_id" :  "507d95d5719dbef170f15bfb" , "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38,"created":"1624374320653" }
{ "_id" :  "507d95d5719dbef170f15bfc" , "name" : "AC3 Case Black", "type" :  "case" , "price" : 12.5,"created":"1624606153646" }
{ "_id" :  "507d95d5719dbef170f15bfd" , "name" : "AC3 Case Red", "type" : "case" , "price" : 12, "created":"1624362066717"}
{ "_id" :  "507d95d5719dbef170f15bfe" , "name" : "Phone Service Basic Plan", "type" : "service", "price":9.5,"created":"1624446320186"}
{ "_id" :  "507d95d5719dbef170f15bff" , "name" : "Phone Service Core Plan", "type" : "service", "price" :3.5,"created":"1624605403064"}
{ "_id" :  "507d95d5719dbef170f15c00" , "name" : "Phone Service Family Plan", "type" : "service", "price":10.4,"created":"1624446320173"}

I want to get the records based month and day and for that, I've written a query like below

db.collection.aggregate([
    { "$group": {
            _id: { month:{ "$month": { "$toDate": "$created" }, day: "$day"  } },
            product: { "$push": "$name" }
    }}
  ])

but it is giving the error

An object representing an expression must have exactly one field: { $month: { $toDate: \"$created\" }, day: \"$day\" }

Expected output

 {
      month:5
      day:12
      products:[
          {
            "name" : "Phone Service Family Plan"
          },
          {"name" : "Phone Service Core Plan"}
      ]
  }

Upvotes: 1

Views: 155

Answers (1)

mickl
mickl

Reputation: 49945

You need to convert your string to long first by using $toLong and also use $dayOfMonth operator since there's no $day in MongoDB:

db.collection.aggregate([
    {
        "$group": {
            _id: {
                month: { "$month": { "$toDate": { $toLong: "$created" } } },
                day: { "$dayOfMonth": { "$toDate": { $toLong: "$created" } } }
                
            },
            product: {
                "$push": "$name"
                }
            }
    },
    {
        $group: {
            _id: "$_id.month",
            monthDays: {
                $push: {
                    day: "$_id.day",
                    product: "$product"
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            month: "$_id",
            monthDays: 1
        }
    },
])

Mongo Playground

Upvotes: 1

Related Questions