How to insert a document with date in MongoDB?

MongoDBDatabaseBig Data Analytics

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")
}
raja
Published on 12-Apr-2019 07:31:56
Advertisements