Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Inserting Date in MongoDB through Mongo Shell



In order to insert Date() in MongoDB through Mongo shell, use the following syntax

var yourVariableName= new Date(year,month, day, hour, minute);
db.yourCollectionName({yourDateFieldName:yourVariableName});

Let us first create a date variable

> var creatingDate = new Date(2019, 03, 29, 13, 12);

Let us create a collection with documents:

>db.insertingDateUsingVariableDemo.insertOne({"UserName":"John","UserMessages":["Hi","Hello","Awesome"],"UserPostDate":creatingDate});

Following is the query to display all documents from a collection with the help of find() method

> db.insertingDateUsingVariableDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9d1b19a629b87623db1b21"),
   "UserName" : "John",
   "UserMessages" : [
      "Hi",
      "Hello",
      "Awesome"
   ],
   "UserPostDate" : ISODate("2019-04-29T07:42:00Z")
}
Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements