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
Selected Reading
How to filter a query on specific date format with MongoDB?
To filter a query on specific date format, use $dateToString. Let us create a collection with documents −
> db.demo433.insertOne({"DueDate":new Date("2019-11-23")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e771278bbc41e36cc3cae91")
}
> db.demo433.insertOne({"DueDate":new Date("2020-01-03")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e771290bbc41e36cc3cae92")
}
Display all documents from a collection with the help of find() method −
> db.demo433.find();
This will produce the following output −
{ "_id" : ObjectId("5e771278bbc41e36cc3cae91"), "DueDate" : ISODate("2019-11-23T00:00:00Z") }
{ "_id" : ObjectId("5e771290bbc41e36cc3cae92"), "DueDate" : ISODate("2020-01-03T00:00:00Z") }
Following is the query to filter a query on specific date format in MongoDB −
> db.demo433.aggregate([
... { $addFields: {stringDate: { $dateToString: { format: "%Y-%m-%d", date: "$DueDate" } } } },
... { $match: {"stringDate":"2020-01-03"}},
... { $project:{"stringDate":0}}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e771290bbc41e36cc3cae92"), "DueDate" : ISODate("2020-01-03T00:00:00Z") } Advertisements
