Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nhapentor/b270ebaf667fa7b066f5f705a8dcf524 to your computer and use it in GitHub Desktop.
Save nhapentor/b270ebaf667fa7b066f5f705a8dcf524 to your computer and use it in GitHub Desktop.
Aggregation pipeline to convert ISODate to desired string format in MongoDB prior to v3.0

Convert Date Format with MongoDB Aggregation

The following aggregation pipeline is used to convert ISODate to desired string format before MongoDB started providing $dateToStringoperator in v3.0

{
  $project: {
    day: { $dayOfMonth: "$LastUpdate" },
    month: { $month: "$LastUpdate" },
    year: { $year: "$LastUpdate" },
  }
}, {
  $project: {
    day: {
      $cond: {
        if: { $lt: [ "$day", 10 ] },
        then: {
          $concat: [
            "0",
            { $substr: [ "$day", 0, 2 ] }
          ]
        },
        else: { $substr: [ "$day", 0, 2 ] }
      }
    },
    month: {
      $cond: {
        if: { $lt: [ "$month", 10 ] },
        then: {
          $concat: [
            "0",
            { $substr: [ "$month", 0, 2 ] }
          ]
        },
        else: { $substr: [ "$month", 0, 2 ] }
      }
    },
    year: { $substr: [ "$year", 0, 4 ] },
  }
}, {
  $project: {
    date: {
      $concat: [
        { $substr: [ "$year", 0, 4 ] },
        "-",
        { $substr: [ "$month", 0, 2 ] },
        "-",
        { $substr: [ "$day", 0, 2 ] }
      ]
    }
  }
}, {
  $group: {
    _id: "$date",
    count: { $sum: 1 }
  }
}

It's a modification from this Stack Overflow's answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment