- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert a document with date in MongoDB?
To insert a document with date in MongoDB, use Date(). Following is the syntax
“yourFieldName”:new Date(yourDateValue);
Let us create a collection with documents. Following is the query
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Larry","UserMessage":"Hi","UserMessagePostDate":new Date("2012-09-24")}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cca58a629b87623db1b16") } >db.insertDocumentWithDateDemo.insertOne({"UserName":"Chris","UserMessage":"Hello","UserMessagePostDate":new Date("2015-12-31")}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cca71a629b87623db1b17") } >db.insertDocumentWithDateDemo.insertOne({"UserName":"Robert","UserMessage":"Bye","UserMessagePostDate":new Date("2019-01-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cca85a629b87623db1b18") }
Following is the query to display all documents from a collection with the help of find() method
> db.insertDocumentWithDateDemo.find().pretty();
This will produce the following output
{ "_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") }
- Related Articles
- How to insert Date in MongoDB?
- How to insert a document into a MongoDB collection using Java?
- How to insert multiple document into a MongoDB collection using Java?
- How to insert date in single quotes with MySQL date formats?
- Conditional upsert (multiple insert) when updating document in MongoDB?
- How to insert DATE in MySQL table with TRIGGERS?
- How to delete a document in MongoDB?
- Update only a single MongoDB document without deleting any date
- How to add a sub-document to sub-document array in MongoDB?
- Find a document with ObjectID in MongoDB?
- How to insert date record to the same table with different date formats with MySQL?
- MongoDB query to find oldest date of three keys in each document
- Insert MongoDB document field only when it's missing?
- How to match date with MongoDB $match?
- How to insert current date/ time using now() in a field with MySQL?

Advertisements