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

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

问题描述

我的每日收藏有以下文档:

..
{ "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天全站免登陆