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
MongoDB query to search date records using only Month and Day
To search MongoDB documents using only month and day while ignoring the year, use the $where operator with JavaScript functions like getMonth() and getDate().
Syntax
db.collection.find({
$where: function() {
return this.dateField.getMonth() == monthValue &&
this.dateField.getDate() == dayValue;
}
});
Sample Data
db.demo181.insertMany([
{"ShippingDate": new ISODate("2020-01-10")},
{"ShippingDate": new ISODate("2019-12-11")},
{"ShippingDate": new ISODate("2018-01-10")},
{"ShippingDate": new ISODate("2020-10-12")}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e398a699e4f06af551997fe"),
ObjectId("5e398a729e4f06af551997ff"),
ObjectId("5e398a7d9e4f06af55199800"),
ObjectId("5e398a879e4f06af55199801")
]
}
Display All Documents
db.demo181.find();
{ "_id": ObjectId("5e398a699e4f06af551997fe"), "ShippingDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("5e398a729e4f06af551997ff"), "ShippingDate": ISODate("2019-12-11T00:00:00Z") }
{ "_id": ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate": ISODate("2018-01-10T00:00:00Z") }
{ "_id": ObjectId("5e398a879e4f06af55199801"), "ShippingDate": ISODate("2020-10-12T00:00:00Z") }
Example: Search by Month OR Day
Find documents where month is February (1) OR day is 10 ?
db.demo181.find({
$where: function() {
return this.ShippingDate.getMonth() == 1 ||
this.ShippingDate.getDate() == 10;
}
});
{ "_id": ObjectId("5e398a699e4f06af551997fe"), "ShippingDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate": ISODate("2018-01-10T00:00:00Z") }
Example: Search by Month AND Day
Find documents for January 10th (any year) ?
db.demo181.find({
$where: function() {
return this.ShippingDate.getMonth() == 0 &&
this.ShippingDate.getDate() == 10;
}
});
{ "_id": ObjectId("5e398a699e4f06af551997fe"), "ShippingDate": ISODate("2020-01-10T00:00:00Z") }
{ "_id": ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate": ISODate("2018-01-10T00:00:00Z") }
Key Points
-
getMonth()returns 0-based index: January = 0, February = 1, December = 11 -
getDate()returns the day of month (1-31) - Use
&&for AND conditions,||for OR conditions -
$whereevaluates JavaScript, so it's slower than regular operators
Conclusion
Use $where with getMonth() and getDate() functions to search MongoDB documents by month and day while ignoring the year. Remember that months are zero-indexed in JavaScript.
Advertisements
