skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. Use this

    db.collection.aggregate([
       {
          $group: {
             _id: { $dateTrunc: { date: "$timeplay", unit: "day" } },
             listeners: { $sum: '$count' }
          }
       }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search