Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

Convert date to date datatype

Issue

I have a date input that is being inserted into MongoDB as a string instead of a date type. I need to insert it as a date type like 2022-06-01T12:00:00.000+00:00. Does anyone know how to do this?

Resolution

To insert a date as a date type in MongoDB, we need to use the "$date" operator. The format for using it is "myDate": {"$date": "DATESTRING"} in the insert query.

For example, let's say we have a JavaScript date object "myDate" that we want to insert into MongoDB as a date type. We can convert it to the required string format using the toISOString() method, and then use the "$date" operator in the insert query:

const myDate = new Date("2022-06-02T05:30:00.000Z");

db.collection.insertOne({
"myDate": {"$date": myDate.toISOString()}
});

In this example, we're inserting the date into a collection called "collection" in the default database. Note that we're using the "toISOString()" method to convert the date object to the required string format.

When we run the insert query, MongoDB will store the "myDate" field as a date type. Later, when we query the collection, we can use date operators like "$lt" or "$gte" to filter the results based on date values.