Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to insert a document with date in MongoDB?
To insert a document with date in MongoDB, use the new Date() constructor to create date values. MongoDB stores dates as ISODate objects in UTC format.
Syntax
db.collection.insertOne({
"fieldName": new Date("YYYY-MM-DD")
});
Example
Let us create a collection with documents containing date fields ?
db.insertDocumentWithDateDemo.insertMany([
{
"UserName": "Larry",
"UserMessage": "Hi",
"UserMessagePostDate": new Date("2012-09-24")
},
{
"UserName": "Chris",
"UserMessage": "Hello",
"UserMessagePostDate": new Date("2015-12-31")
},
{
"UserName": "Robert",
"UserMessage": "Bye",
"UserMessagePostDate": new Date("2019-01-01")
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9cca58a629b87623db1b16"),
ObjectId("5c9cca71a629b87623db1b17"),
ObjectId("5c9cca85a629b87623db1b18")
]
}
Verify Result
Display all documents from the collection using find() ?
db.insertDocumentWithDateDemo.find().pretty();
{
"_id": ObjectId("5c9cca58a629b87623db1b16"),
"UserName": "Larry",
"UserMessage": "Hi",
"UserMessagePostDate": ISODate("2012-09-24T00:00:00Z")
}
{
"_id": ObjectId("5c9cca71a629b87623db1b17"),
"UserName": "Chris",
"UserMessage": "Hello",
"UserMessagePostDate": ISODate("2015-12-31T00:00:00Z")
}
{
"_id": ObjectId("5c9cca85a629b87623db1b18"),
"UserName": "Robert",
"UserMessage": "Bye",
"UserMessagePostDate": ISODate("2019-01-01T00:00:00Z")
}
Key Points
- Use
new Date("YYYY-MM-DD")format for date strings - MongoDB automatically converts dates to ISODate format in UTC
- You can also use
new Date()without parameters for current timestamp
Conclusion
The new Date() constructor allows easy insertion of date fields in MongoDB documents. All dates are stored as ISODate objects in UTC format for consistency across different time zones.
Advertisements
