查找过去7天当天的最后一个文档

Pas*_*nes 2 javascript mongoose mongodb node.js

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

这是我的架构:

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

编辑

我已经尝试过使用这个静态,但它会将完全相同的记录拉7次

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)
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Lef*_*ium 6

Kristina Chodorow在她的书MongoDB:The Definitive Guide中给出了这个确切任务的详细配方:

假设我们有一个跟踪股票价格的网站.每隔几分钟从上午10点到下午4点,它获得一个股票的最新价格,它存储在MongoDB中.现在,作为报告应用程序的一部分,我们希望找到过去30天的收盘价.这可以使用组轻松完成.

我对Mongoose并不熟悉,但是我试图让她的例子适应你的情况.注意我将createdAt default属性从值更改为函数,并datestamp在架构中添加了一个额外的字段:

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()

);
Run Code Online (Sandbox Code Playgroud)