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
Convert date parts to date in MongoDB
To convert separate date parts (year, month, day) into a complete date in MongoDB, use the $dateFromParts operator within an aggregation pipeline. This operator combines individual date components into a proper date object.
Syntax
db.collection.aggregate([
{
$project: {
dateField: {
$dateFromParts: {
year: "$yearField",
month: "$monthField",
day: "$dayField"
}
}
}
}
]);
Sample Data
db.demo386.insertOne({
details: {
Month: 02,
Day: 27,
Year: 2020
}
});
{ "acknowledged": true, "insertedId": ObjectId("...") }
db.demo386.find();
{ "_id": ObjectId("5e5bd9a222064be7ab44e7f7"), "details": { "Month": 2, "Day": 27, "Year": 2020 } }
Example: Convert Date Parts to Formatted Date String
db.demo386.aggregate([
{
$project: {
_id: 0,
DueDate: {
$dateToString: {
format: "%m-%d-%Y",
date: {
$dateFromParts: {
year: "$details.Year",
month: "$details.Month",
day: "$details.Day"
}
}
}
}
}
}
]);
{ "DueDate": "02-27-2020" }
Key Points
-
$dateFromPartscreates a date object from separate year, month, and day values. - Combine with
$dateToStringto format the resulting date as needed. - The operator also accepts hour, minute, second, and millisecond for precise timestamps.
Conclusion
Use $dateFromParts in aggregation pipelines to construct complete dates from individual date components. This approach is essential when working with data where dates are stored as separate fields rather than proper date objects.
Advertisements
