To get component of Date/ISODate in MongoDB, let us create a document with date in the collection. Now let us get the component of Date/ISODate in MongoDB
> db.componentOfDateDemo.insert({"ShippingDate":new Date()}); WriteResult({ "nInserted" : 1 })
Following is the query to display all documents from a collection with the help of find() method
> db.componentOfDateDemo.find().pretty()
This will produce the following output
{ "_id" : ObjectId("5c9e9d57d628fa4220163b68"), "ShippingDate" : ISODate("2019-03-29T22:33:59.776Z") }
Following is the query to get result using findOne()
> var result=db.componentOfDateDemo.findOne();
Now you can display documents from the collection. Following is the query
> result
This will produce the following output
{ "_id" : ObjectId("5c9e9d57d628fa4220163b68"), "ShippingDate" : ISODate("2019-03-29T22:33:59.776Z") }
To get only Date from documents, use the following query
> result.ShippingDate;
This will produce the following output
ISODate("2019-03-29T22:33:59.776Z")
In order to get all the details about the Date, use the following query
> result.ShippingDate.pressTABKeyTwoTimes
Following is the screenshot of the output
Now you can use the above function for field “ShippingDate”. Following is the query
> result.ShippingDate.getFullYear() 2019 > result.ShippingDate.getSeconds(); 59 > result.ShippingDate.getMinutes(); 3 > result.ShippingDate.getHours(); 4 > result.ShippingDate.getDate(); 30 > result.ShippingDate.getMonth(); 2