How to insert Date in MongoDB?

MongoDBDatabaseBig Data Analytics

To insert date in MongoDB, use Date(). Let us create a collection with documents −

> db.demo421.insert({"DueDate":new Date(Date.now())});
WriteResult({ "nInserted" : 1 })
> db.demo421.insert({"DueDate":new Date("2020-01-15")});
WriteResult({ "nInserted" : 1 })
> db.demo421.insert({"DueDate":new Date("2018-12-31")});
WriteResult({ "nInserted" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo421.find();

This will produce the following output −

{ "_id" : ObjectId("5e73a2ec9822da45b30346de"), "DueDate" : ISODate("2020-03-19T16:50:52.746Z") }
{ "_id" : ObjectId("5e73a2fb9822da45b30346df"), "DueDate" : ISODate("2020-01-15T00:00:00Z") }
{ "_id" : ObjectId("5e73a3079822da45b30346e0"), "DueDate" : ISODate("2018-12-31T00:00:00Z") }
raja
Published on 03-Apr-2020 13:46:44
Advertisements