How to convert string to Date object in MongoDB

(moment(table1.selectedRow.data.Date).toString())

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.

https://docs.retool.com/docs/mongodb

Example:

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

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

date: (moment(table1.selectedRow.data.Date).toString())

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

image

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: https://docs.mongodb.com/manual/reference/mongodb-extended-json/#mongodb-bsontype-Date

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 table1.selectedRow.data.Date
You need to tell momentjs how to parse your date if you need to convert to string to moment object: Moment.js | Docs
Like:

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

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

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

# OR with canonical mode
const request = {
  date: {
    "$date": moment(table1.selectedRow.data.Date, "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!