Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get component of Date / ISODate in MongoDB?
To get component of Date/ISODate in MongoDB, you can access individual date components like year, month, day, hour, minute, and second using JavaScript date methods on the ISODate field.
Syntax
// Access date field var dateField = db.collection.findOne().dateFieldName; // Get components dateField.getFullYear() // Year (e.g., 2019) dateField.getMonth() // Month (0-11, January=0) dateField.getDate() // Day of month (1-31) dateField.getHours() // Hour (0-23) dateField.getMinutes() // Minutes (0-59) dateField.getSeconds() // Seconds (0-59)
Create Sample Data
db.componentOfDateDemo.insertOne({
"ShippingDate": new Date()
});
{
"acknowledged": true,
"insertedId": ObjectId("...")
}
Verify the Document
db.componentOfDateDemo.findOne();
{
"_id": ObjectId("5c9e9d57d628fa4220163b68"),
"ShippingDate": ISODate("2019-03-29T22:33:59.776Z")
}
Extract Date Components
Store the document in a variable and access date components ?
var result = db.componentOfDateDemo.findOne(); result.ShippingDate.getFullYear(); result.ShippingDate.getMonth(); result.ShippingDate.getDate(); result.ShippingDate.getHours(); result.ShippingDate.getMinutes(); result.ShippingDate.getSeconds();
2019 2 30 4 3 59
Key Points
-
getMonth()returns 0−11 (January = 0, March = 2) -
getDate()returns day of month (1−31) - Time components reflect UTC timezone in ISODate
- Use
getDay()for day of week (0−6, Sunday = 0)
Conclusion
Access individual date components in MongoDB by storing the document in a variable and using JavaScript date methods like getFullYear(), getMonth(), and getDate() on the ISODate field.
Advertisements
