查找过去7天当天的最后一个文档 [英] Find last document of the day for the last 7 days

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

问题描述

我每小时都会向架构添加一个条目,以便跟踪当天的增长情况,同时保持当前的当前分数。现在我希望能够提取过去一周每天的最新记录。结果将是6个记录,在午夜或午夜左右,前6天,第7个记录是当天的最新记录。

I am adding entries to a schema every hour in order to track growth over the course of days while maintaining a current score for the current day. Now I would like to be able to pull the most recent record for each day for the past week. The results would be 6 records at or around midnight for 6 days previous and the 7th being the latest for the current day.

这是我的架构:

var schema = new Schema({
  aid: { type: Number }
, name: { type: String }
, score: { type: Number }
, createdAt: { type: Date, default: Date.now() }
})

编辑

我尝试过使用此静态,但它会拉动完全相同的记录7次

I've tried using this static, but it pulls the exact same record 7 times

schema.statics.getLastWeek = function(name, fn) {
  var oneday = 60 * 60 * 24
    , now = Date.now()
    , docs = []

  for (var i = 1; i <= 7; i++) {
    this.where('name', new RegExp(name, 'i'))
    .where('createdAt')
    .gte(now - (i * oneday))
    .desc('createdAt')
    .findOne(function(err,doc){
      docs.push(doc)
    })
  }
}

如果我使用的是SQL,我会选择MAXDATE进行子查询并将其连接到我的主查询,以便检索我想要的结果。无论如何要在这里做到这一点?

If I were using SQL I would do a subquery selecting MAXDATE and join it to my main query in order to retrieve the results I want. Anyway to do this here?

推荐答案

Kristina Chodorow在她的书 MongoDB中给出了这个确切任务的详细配方:权威指南

Kristina Chodorow gives a detailed recipe for this exact task in her book MongoDB: The Definitive Guide:


假设我们有一个跟踪股票价格的网站。从上午10点到下午4点每隔几美元b b分钟,它获得一个股票的最新价格,它存储在MongoDB中的
。现在,作为报告申请的一部分,
我们想要找到过去30天的收盘价。这可以通过组轻松完成

Suppose we have a site that keeps track of stock prices. Every few minutes from 10 a.m. to 4 p.m., it gets the latest price for a stock, which it stores in MongoDB. Now, as part of a reporting application, we want to find the closing price for the past 30 days. This can be easily accomplished using group.

我不熟悉Mongoose,但是我试图适应她的例子如下。注意我将 createdAt 默认属性从值更改为函数并添加了一个额外字段 datestamp 到您的架构:

I'm not familiar with Mongoose, however I've tried to adapt her example to your case below. Note I changed the createdAt default property from a value to a function and added an extra field datestamp to your schema:

var oneday = 24 * 60 * 60;

var schema = new Schema({
  aid: { type: Number }
, name: { type: String }
, score: { type: Number }

  // default: is a function and called every time; not a one-time value!
, createdAt: { type: Date, default: Date.now }

  // For grouping by day; documents created on same day should have same value
, datestamp: { type: Number
             , default: function () { return Math.floor(Date.now() / oneday); }
             }
});


schema.statics.getLastWeek = function(name, fn) {
    var oneweekago = Date.now() - (7 * oneday);

    ret = this.collection.group({
          // Group by this key. One document per unique datestamp is returned.
          key: "datestamp"
          // Seed document for each group in result array.
        , initial: { "createdAt": 0 }
          // Update seed document if more recent document found.
        , reduce: function(doc, prev) {
              if (doc.createdAt > prev.createdAt) {
                prev.createdAt = doc.createdAt;
                prev.score = doc.score;

                // Add other fields, if desired:
                prev.name = doc.name;
              }
          // Process only documents created within past seven days
        , condition: { "createdAt" : {"$gt": oneweekago} }
        }});

   return ret.retval;

   // Note ret, the result of group() has other useful fields like:
   // total "count" of documents,
   // number of unique "keys",
   // and "ok" is false if a problem occurred during group()

);

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

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