Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fetch month, day, year, etc. from ISODate in MongoDB?
The mongo shell provides various methods like ISODate() to return the date, either as a string or as a Date object. ISODate() constructor returns a Date object using the ISODate() wrapper.
Let us create a collection with documents −
> db.demo548.insertOne({"dueDate":new ISODate("2020-04-09 12:12:40")});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8e30499e5f92834d7f05de")
}
Display all documents from a collection with the help of find() method −
> db.demo548.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e30499e5f92834d7f05de"), "dueDate" : ISODate("2020-04-
09T12:12:40Z") }
Following is the query to display, month, day, week, year, etc. from ISODate −
> db.demo548.aggregate( [ { $project: { Year: { $year: "$dueDate"
}, Month: { $month: "$dueDate" }, Day: { $dayOfMonth: "$dueDate"
}, Hour: { $hour: "$dueDate" }, Minutes: { $minute: "$dueDate" },
Seconds: { $second: "$dueDate" }, Milliseconds: { $millisecond: "$dueDate" },
DayOfYear: { $dayOfYear: "$dueDate" }, DayOfWeek: { $dayOfWeek: "$dueDate"
}, Week: { $week: "$dueDate" } } } ] ).pretty();
This will produce the following output −
{
"_id" : ObjectId("5e8e30499e5f92834d7f05de"),
"Year" : 2020,
"Month" : 4,
"Day" : 9,
"Hour" : 12,
"Minutes" : 12,
"Seconds" : 40,
"Milliseconds" : 0,
"DayOfYear" : 100,
"DayOfWeek" : 5,
"Week" : 14
}Advertisements