- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to search for Month and Day only?
To search for month and day only, use the aggregate framework.
Let us first create a collection with documents −
> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2019-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcaeef71edecf6a1f6b2") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-30")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcb7ef71edecf6a1f6b3") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbcbcef71edecf6a1f6b4") } > db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2016-04-27")}); { "acknowledged" : true, "insertedId" : ObjectId("5cefbdaaef71edecf6a1f6b5") }
Display all documents from a collection with the help of find() method −
> db.monthAndDayDemo.find();
Output
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") } { "_id" : ObjectId("5cefbcb7ef71edecf6a1f6b3"), "LoginDate" : ISODate("2018-04-30T00:00:00Z") } { "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "LoginDate" : ISODate("2018-04-27T00:00:00Z") } { "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "LoginDate" : ISODate("2016-04-27T00:00:00Z") }
Following is the query to search for month and day only −
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") } > db.monthAndDayDemo.aggregate( { "$project": { "m":{"$month":"$LoginDate"}, "d": { "$dayOfMonth":"$LoginDate" } }}, { "$match":{ "m": 4, "d": 27 } } );
Output
{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "m" : 4, "d" : 27 } { "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "m" : 4, "d" : 27 } { "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "m" : 4, "d" : 27 }
Advertisements