Mongo搜索月份和日期仅限

Mongo Search for Month and Day Only

本文关键字:日期 搜索 Mongo      更新时间:2023-09-26

我希望能够做一个Mongo搜索所有记录匹配的日期和月份,但不是年。例如,给定如下的记录集:

{
    "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"),
}

我希望在传递某种形式的05/29

时返回a和b

您可以使用$where条件

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

您应该将变量'month'和'day'替换为您想要使用的实际值。

尝试下面的聚合查询。请查看$dayOfMonth和$month了解更多细节。

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