MongoDB 查找查询与 CurrentDate 的比较 [英] MongoDB find Query comparision with CurrentDate

查看:83
本文介绍了MongoDB 查找查询与 CurrentDate 的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 MongoDB 集合中获取当天的文档.我的文档如下所示:

I want to fetch current day documents from a MongoDB collection. My documents look like this:

{ 
    "_id" : ObjectId("55743941789a9abe7f4af3fd"), 
    "msisdn" : "9xxxxxxxxxx", 
    "act_date" : ISODate("2014-11-24T00:00:00Z"), 
    "date" : ISODate("2015-06-07T00:00:00Z"), 
    "recharge" : { "recharge_amt" : 0, "rechargetype" : "WEB" },
    "voice" : { "local_og_mou" : 20, "local_other_mobile_og_mou" : 0, "nld_og_mou" : 0, "nld_other_mobile_og_mou" : 10 }, 
    "gprs" : { "total_access_count" : 1, "total_datavolume_mb" : 42 }, 
    "sms" : { "freesms" : 3, "local_sms_count" : 0, "nat_sms_count" : 0, "inter_sms_count" : 0 } 
}

推荐答案

根据您的问题您想从 mongodb 集合中获取当前日期的文档.在 mongoDB shell 中,当您键入 new Date() 时,它会为您提供当前日期和时间,并且当您运行相同的 new Date() 时,该值总是会有所不同,因此您的查询可能是这样的:

As per your question you want to fetch current day documents from a mongodb collection. In mongoDB shell when you type new Date() it gives you current date with time and this value always vary when you run same new Date() so probably your query like this :

db.collectionName.find({"start_date":new Date()}).pretty()

但是,我认为此查询返回将出现在您的集合中的那些文档,但您的文档中可能不存在相同的当前 Date 值,因此在这种情况下,您应该使用以下

But, I think this query return the those documents which will presents in your collection but same current Date value may be not presents in your documents SO this case you should use following

db.collectionName.find({"start_date":{"$lte":new Date()}}).pretty()

或者

db.collectionName.find({"start_date":{"$gte":new Date()}}).pretty()

在某些情况下,如果您想找到与 year,month,day 完全匹配的,那么您应该使用 聚合$year,$month,$dayOfMonth 在 $project 中是这样的:

In some case If you want to find exact match with year,month,day then you should use aggregation with $year,$month,$dayOfMonth in $project like this :

db.collectionName.aggregate({
  "$project": {
    "year": {
      "$year": "$date"
    },
    "month": {
      "$month": "$date"
    },
    "day": {
      "$dayOfMonth": "$date"
    }
  }
}, {
  "$match": {
    "year": new Date().getFullYear(),
    "month": new Date().getMonth() + 1, //because January starts with 0
    "day": new Date().getDate()
  }
})

在上面的聚合查询中,将返回那些匹配当前日期的文档,如当前日期的year,month,day.你也将 $match 替换为

In above aggregation query will return those documents which match current date like year,month,day of current date. Also you replace $match as

var currentDate = new Date()

 {
  "$match": {
    "year": currentDate.getFullYear(),
    "month": currentDate.getMonth() + 1, //because January starts with 0
    "day": currentDate.getDate()
  }
}

这篇关于MongoDB 查找查询与 CurrentDate 的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆