skip to Main Content

I am using this code in MongoDB aggregation:

{
  date: ISODate()
}

It’s generating current date in ISO format for every document.

How can I generate random ISO date for every document?

2

Answers


  1. The mongoDB docs on Date() / ISODate() say

    You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:

    The listed options state you can pass an integer to ISODate() in milliseconds since the UNIX Epoch (Jan 1st 1970)

    With this info you could generate a random integer between whatever starting date in milliseconds and the current date in milliseconds and pass that to the ISODate() function upon document creation giving it a random date.
    Note you’d need to generate a new random date for each document if you want them to be different.

    Here is a working example in Node.js

    function getRandomTimestamp () {
      // 1577854800 is the timestamp for 2020-01-01 00:00:00
      const minDate = 1577854800
      return Math.floor(Math.random() * (Date.now() - minDate) + minDate)
    }
    Login or Signup to reply.
  2. Try to use $rand and multiply the current UNIX timestamp with it:

    db.collection.aggregate({
      "$project": {
        "date": {
          $toDate: {
            $multiply: [
              {
                $rand: {}
              },
              {
                $subtract: [
                  new Date(),
                  new Date("1970-01-01")
                ]
              }
            ]
          }
        }
      }
    })
    

    Link to playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search