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?
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
The mongoDB docs on Date() / ISODate() say
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
Try to use
$rand
and multiply the current UNIX timestamp with it:Link to playground