查找过去n天内的所有文档 [英] Find all documents within last n days

查看:47
本文介绍了查找过去n天内的所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的每日收藏包含以下文档:

My daily collection has documents like:

..
{ "date" : ISODate("2013-01-03T00:00:00Z"), "vid" : "ED", "san" : 7046.25, "izm" : 1243.96 }
{ "date" : ISODate("2013-01-03T00:00:00Z"), "vid" : "UA", "san" : 0, "izm" : 0 }
{ "date" : ISODate("2013-01-03T00:00:00Z"), "vid" : "PAL", "san" : 0, "izm" : 169.9 }
{ "date" : ISODate("2013-01-03T00:00:00Z"), "vid" : "PAL", "san" : 0, "izm" : 0 }
{ "date" : ISODate("2013-01-03T00:00:00Z"), "vid" : "CTA_TR", "san" : 0, "izm" : 0 }
{ "date" : ISODate("2013-01-04T00:00:00Z"), "vid" : "CAD", "san" : 0, "izm" : 169.9 }
{ "date" : ISODate("2013-01-04T00:00:00Z"), "vid" : "INT", "san" : 0, "izm" : 169.9 }
...

我保留了 _id 字段,以保留此处的空间. 我的任务是在过去15天内获取所有文档".如您所见,我需要某种方式:

I left off _id field to spare the space here. My task is to "fetch all documents within last 15 days". As you can see I need somehow to:

  1. 获取15个唯一的日期.最新的文档应作为集合中的最新文档(我的意思是,今天的日期不是必需的,它只是基于 date 字段的集合中的最新文档),也是最早的文档.好吧,也许没有必要严格定义查询中最古老的一天,如果您知道我的意思,我需要的是从最新的一天开始的top15.就像15天是唯一天.
  2. db.daily.find()所有具有日期字段(在15天之内)的文档.
  1. Get 15 unique dates. The newest one should be takes as the newest document in collection (what I mean that it isn't necessary the today's date, it's just the latest one in collection based on date field), and the oldest.. well, maybe it's not necessary to strictly define the oldest day in query, what I need is some kind of top15 starting from the newest day, if you know what I mean. Like 15 unique days.
  2. db.daily.find() all documents, that have date field in that range of 15 days.

因此,从最新的收藏开始,我应该在15天内看到所有文档.

So, in result, I should see all documents within 15 days starting from the newest in collection.

我该怎么做?

谢谢

推荐答案

我刚刚针对您的数据样本测试了以下查询,并且效果很好:

I just tested the following query against your data sample and it worked perfectly:

db.datecol.find(
{
    "date": 
    {
        $gte: new Date((new Date().getTime() - (15 * 24 * 60 * 60 * 1000)))
    }
}
).sort({ "date": -1 })

这篇关于查找过去n天内的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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