How to convert string to Date object in MongoDB


This just returns the date in an ISO format but it's a string, I want it in a Date object format in MongoDB.
I have been using this and I tried to search a lot for the same on the web but wasn't able to find anything. Any help is appreciated.

Try to use Extended JSON format v2.


$set: {
  updatedAt: {
    $date: {{ dateRange.startValue }}

I am still not able to convert the date strings into Date objects.

date: (moment(

Adding the $ in front of date is giving an error at the time of using the insert query.


I am using the shown queries together to upload the data in the DB but the date issue is not being solved by your answer.
Thanking you in advance.

As I showed in my previous comment, try to use extended json v2 syntax. Something like this:

const request = {
  date: {
    "$date": "2021-10-01T11:55:28.867Z" // This needs a string in ISO format, not a datetime object. 

Note that "$date" is quoted with: "
Your moment object toString() method might not yield in the correct string format.
This might work: toISOString() Check it out here: Moment.js | Docs

The date value has to be either Canonical or Relaxed, stated here:

You can try canonical format with epoch milliseconds. Moment can convert your date to that easily. I think it is .valueOf() method

Provide an example of your datetime string from
You need to tell momentjs how to parse your date if you need to convert to string to moment object: Moment.js | Docs

const myDateTimeString= '24/12/2019 09:15:00';
moment(myDateTimeString, "DD MM YYYY hh:mm:ss");

# Maybe in your case
moment(, "DD MM YYYY hh:mm:ss").toISOString();

# Maybe full example. I am not sure, I did not test this:
const request = {
  date: {
    "$date": moment(, "DD MM YYYY hh:mm:ss").toISOString();

# OR with canonical mode
const request = {
  date: {
    "$date": moment(, "DD MM YYYY hh:mm:ss").valueOf();
1 Like

Thank you so much, Gorkhaan! The first code in your message worked for me!!
The toString() function is yielding the correct Date format in MongoDB.
I appreciate all the help! Thank you!