我每小时都会在架构中添加条目,以便跟踪几天内的增长情况,同时保持当天的当前得分。现在,我希望能够提取过去一周每天的最新记录。结果将是前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:
我对 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/