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
Format date value in MongoDB shell?
To format date values in MongoDB shell, use the $dateToString operator within an aggregation pipeline. This operator converts ISODate values into custom formatted strings according to your specified format pattern.
Syntax
{
"$dateToString": {
"format": "formatString",
"date": "$dateField"
}
}
Sample Data
db.demo480.insertMany([
{ "id": 1, "DueDate": new ISODate("2020-01-10") },
{ "id": 1, "DueDate": new ISODate("2017-12-21") },
{ "id": 1, "DueDate": new ISODate("2019-10-12") },
{ "id": 1, "DueDate": new ISODate("2019-12-01") }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e821056b0f3fa88e2279098"),
ObjectId("5e821062b0f3fa88e2279099"),
ObjectId("5e82106ab0f3fa88e227909a"),
ObjectId("5e821078b0f3fa88e227909b")
]
}
Display all documents from the collection ?
db.demo480.find();
{ "_id": ObjectId("5e821056b0f3fa88e2279098"), "id": 1, "DueDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("5e821062b0f3fa88e2279099"), "id": 1, "DueDate": ISODate("2017-12-21T00:00:00Z") }
{ "_id": ObjectId("5e82106ab0f3fa88e227909a"), "id": 1, "DueDate": ISODate("2019-10-12T00:00:00Z") }
{ "_id": ObjectId("5e821078b0f3fa88e227909b"), "id": 1, "DueDate": ISODate("2019-12-01T00:00:00Z") }
Example: Format Date with Custom Pattern
Format dates as "YYYY-MM-DD HH-MM" and sort by descending date order ?
db.demo480.aggregate([
{ "$match": { "id": 1 } },
{ "$sort": { "DueDate": -1 } },
{
"$project": {
"_id": 0,
"DueDate": {
"$dateToString": {
"format": "%Y-%m-%d %H-%M",
"date": "$DueDate"
}
}
}
}
]);
{ "DueDate": "2020-01-10 00-00" }
{ "DueDate": "2019-12-01 00-00" }
{ "DueDate": "2019-10-12 00-00" }
{ "DueDate": "2017-12-21 00-00" }
Key Points
-
%Y= 4-digit year,%m= month (01-12),%d= day (01-31) -
%H= hour (00-23),%M= minute (00-59),%S= second (00-59) - Use within
$projectstage of aggregation pipeline for formatting output
Conclusion
The $dateToString operator provides flexible date formatting in MongoDB aggregation pipelines. Use format specifiers like %Y-%m-%d to convert ISODate objects into readable string representations.
Advertisements
