我想从MongoDB集合中获取当前文档。我的文档如下所示:
{
"_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()
因此可能是这样的查询:
db.collectionName.find({"start_date":new Date()}).pretty()
但是,我认为此查询返回的是将在您的集合中显示的那些文档,但是Date
您的文档中可能没有相同的当前值,因此在这种情况下,您应该使用以下
db.collectionName.find({"start_date":{"$lte":new Date()}}).pretty()
或者
db.collectionName.find({"start_date":{"$gte":new Date()}}).pretty()
在某些情况下,如果要查找与的完全匹配,则应在$ project中year,month,day
使用$ year,$ month,$ dayOfMonth进行聚合,如下所示:
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
为
var currentDate = new Date()
{
"$match": {
"year": currentDate.getFullYear(),
"month": currentDate.getMonth() + 1, //because January starts with 0
"day": currentDate.getDate()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句