gpt4 book ai didi

javascript - 查找过去 7 天当天的最后一份文件

转载 作者:可可西里 更新时间:2023-11-01 09:57:33 26 4
gpt4 key购买 nike

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

这是我的架构:

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

编辑

我试过使用这个静态的,但它提取了 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)
})
}
}

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

最佳答案

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

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

);

关于javascript - 查找过去 7 天当天的最后一份文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com