简体   繁体   中英

Mongo Search for Month and Day Only

I would like to be able to do a Mongo search for all records matching the day and month, but not the year. For instance, given a record set like the following:

{
    "lastName" : "a",
    "date" : ISODate("1983-05-29T09:32:11.888Z"),
}, {
    "lastName" : "b",
    "date" : ISODate("1959-05-29T09:32:11.888Z"),
}, {
    "lastName" : "c",
    "date" : ISODate("1983-06-29T09:32:11.888Z"),
}

I would like a and b to be returned when passing in some form of 05/29

You could use the $where condition

 db.collection.find({$where : function() { return this.date.getMonth() == month && this.date.getDate() == day} })

You should replace the variables 'month' and 'day' with the actual values you want to use.

Try with below aggregation query. Please look at $dayOfMonth and $month for more details.

db.test.aggregate(
 { "$project": {    
      "lastName": 1,      
      "month":{"$month":"$date"},      
      "day": { "$dayOfMonth":"$date" }  
 },
 { "$match":{           
      "month": 5,       
      "day": 29 
   }
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM