Home > OS >  MongoDB group ISODate but maintain date format
MongoDB group ISODate but maintain date format

Time:06-15

I know I can group data inside a collection by

{
    $group: {
        _id: {
            day: {
                $dayOfMonth: '$timeplay'
            },
            month: {
                $month: '$timeplay'
            },
            year: {
                $year: '$timeplay'
            }
        },
        listeners: {
            $sum: '$count'
        }
    }

However, it does not show the date in ISOdate format anymore which is what I need it to still do.

Is there a way to create ISOdate based on this information? As the output currently looks like the following Current Output

CodePudding user response:

You can use $dateFromParts operator to convert to date from parts,

  {
    $group: {
      _id: {
        $dateFromParts: {
          day: { $dayOfMonth: "$timeplay" },
          month: { $month: "$timeplay" },
          year: { $year: "$timeplay" }
        }
      },
      listeners: { $sum: '$count' }
    }
  }

Playground

CodePudding user response:

Use this

db.collection.aggregate([
   {
      $group: {
         _id: { $dateTrunc: { date: "$timeplay", unit: "day" } },
         listeners: { $sum: '$count' }
      }
   }
])
  • Related