0
0
MongodbHow-ToBeginner · 3 min read

How to Insert Date in MongoDB: Syntax and Examples

To insert a date in MongoDB, use the Date object in your document. You can create a new date with new Date() for the current date and time or pass a date string or timestamp to specify a date.
📐

Syntax

In MongoDB, dates are stored using the Date object. You insert a date by assigning a Date value to a field in your document.

  • new Date(): Creates the current date and time.
  • new Date("YYYY-MM-DD"): Creates a date from a string.
  • new Date(timestamp): Creates a date from a timestamp in milliseconds.
mongodb
db.collection.insertOne({ event: "meeting", date: new Date() })
💻

Example

This example inserts a document with a date field set to the current date and time, and another document with a specific date.

mongodb
db.events.insertMany([
  { name: "Conference", date: new Date() },
  { name: "Holiday", date: new Date("2024-12-25T00:00:00Z") }
])
Output
{ "acknowledged" : true, "insertedIds" : [ ObjectId("..."), ObjectId("...") ] }
⚠️

Common Pitfalls

Common mistakes when inserting dates in MongoDB include:

  • Inserting dates as strings instead of Date objects, which prevents date queries.
  • Using incorrect date string formats that MongoDB cannot parse.
  • Forgetting to use new Date() and inserting the constructor itself as a value.
mongodb
/* Wrong: date as string */
db.events.insertOne({ name: "WrongDate", date: "2024-12-25" })

/* Right: date as Date object */
db.events.insertOne({ name: "RightDate", date: new Date("2024-12-25T00:00:00Z") })
📊

Quick Reference

UsageDescription
new Date()Current date and time
new Date("YYYY-MM-DD")Specific date from string
new Date(timestamp)Date from milliseconds timestamp

Key Takeaways

Always use the Date object to store dates in MongoDB for proper querying.
Use new Date() for the current date and new Date("YYYY-MM-DD") for specific dates.
Avoid storing dates as plain strings to ensure correct date operations.
Check date string formats to prevent parsing errors.
Use insertOne or insertMany with Date objects to add date fields.