How can I save new Date() in MongoDB?

To save new Date() in MongoDB, use new ISODate() or new Date() for date and datetime values. MongoDB automatically stores dates in BSON Date format, which is represented as ISODate in the shell.

Syntax

// Using ISODate
db.collection.insertOne({
    "field": new ISODate("YYYY-MM-DD HH:MM:SS")
});

// Using Date
db.collection.insertOne({
    "field": new Date("YYYY-MM-DD HH:MM:SS")
});

Create Sample Data

Insert documents with date fields using new ISODate() ?

db.saveDateDemo.insertMany([
    {
        "UserName": "John",
        "UserLoginDatetime": new ISODate('2018-01-31 12:34:56')
    },
    {
        "UserName": "Alice",
        "UserLoginDatetime": new ISODate('2019-02-01 04:01:10')
    },
    {
        "UserName": "Bob",
        "UserLoginDatetime": new ISODate('2019-04-22 12:36:45')
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cbd67d4de8cc557214c0e04"),
        ObjectId("5cbd67e8de8cc557214c0e05"),
        ObjectId("5cbd6805de8cc557214c0e06")
    ]
}

Display Documents

Retrieve all documents to verify the date storage ?

db.saveDateDemo.find().pretty();
{
    "_id": ObjectId("5cbd67d4de8cc557214c0e04"),
    "UserName": "John",
    "UserLoginDatetime": ISODate("2018-01-31T12:34:56Z")
}
{
    "_id": ObjectId("5cbd67e8de8cc557214c0e05"),
    "UserName": "Alice",
    "UserLoginDatetime": ISODate("2019-02-01T04:01:10Z")
}
{
    "_id": ObjectId("5cbd6805de8cc557214c0e06"),
    "UserName": "Bob",
    "UserLoginDatetime": ISODate("2019-04-22T12:36:45Z")
}

Current Date Example

Save the current date and time using new Date() without parameters ?

db.saveDateDemo.insertOne({
    "UserName": "Current User",
    "UserLoginDatetime": new Date()
});

Key Points

  • Both new ISODate() and new Date() work in MongoDB shell
  • MongoDB stores dates as BSON Date type, displayed as ISODate format
  • Dates are automatically converted to UTC timezone for storage
  • Use new Date() without parameters for current timestamp

Conclusion

Use new ISODate() or new Date() to save date values in MongoDB. The database automatically handles conversion to BSON Date format and stores them in UTC timezone for consistent date operations.

Updated on: 2026-03-15T00:50:57+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements