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
How to filter a query on specific date format with MongoDB?
To filter a query on specific date format in MongoDB, use the $dateToString operator within an aggregation pipeline to convert dates to string format and then match against the desired date pattern.
Syntax
db.collection.aggregate([
{ $addFields: { stringDate: { $dateToString: { format: "%Y-%m-%d", date: "$dateField" } } } },
{ $match: { "stringDate": "YYYY-MM-DD" } },
{ $project: { "stringDate": 0 } }
]);
Sample Data
db.demo433.insertMany([
{ "DueDate": new Date("2019-11-23") },
{ "DueDate": new Date("2020-01-03") }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e771278bbc41e36cc3cae91"),
ObjectId("5e771290bbc41e36cc3cae92")
]
}
Display all documents from the collection ?
db.demo433.find();
{ "_id": ObjectId("5e771278bbc41e36cc3cae91"), "DueDate": ISODate("2019-11-23T00:00:00Z") }
{ "_id": ObjectId("5e771290bbc41e36cc3cae92"), "DueDate": ISODate("2020-01-03T00:00:00Z") }
Example: Filter by Specific Date
Filter documents where DueDate matches "2020-01-03" in YYYY-MM-DD format ?
db.demo433.aggregate([
{ $addFields: { stringDate: { $dateToString: { format: "%Y-%m-%d", date: "$DueDate" } } } },
{ $match: { "stringDate": "2020-01-03" } },
{ $project: { "stringDate": 0 } }
]);
{ "_id": ObjectId("5e771290bbc41e36cc3cae92"), "DueDate": ISODate("2020-01-03T00:00:00Z") }
How It Works
-
$addFieldscreates a temporary stringDate field with the formatted date string -
$dateToStringconverts the Date object to "YYYY-MM-DD" format using%Y-%m-%d -
$matchfilters documents where the string date equals the target value -
$projectremoves the temporary stringDate field from the final output
Conclusion
Use $dateToString in an aggregation pipeline to filter dates by specific string formats. This approach converts Date objects to strings for precise pattern matching while preserving the original date fields in results.
Advertisements
