一种解决方案是使用 group() 按天对记录进行分组。它很花哨、很慢并且可能会阻塞(意味着没有其他东西可以同时运行),但如果你的记录集不是太大,它非常强大。
群组:http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group
至于 mongoose,我不确定它是否直接支持 group(),但您可以使用 node-mongodb-native 实现,通过执行以下操作(主要是伪代码):
schema.statics.getLastWeek = function(name, cb) {
var keys = {} // can't remember what this is for
var condition = {} // maybe restrict to last 7 days
var initial = {day1:[],day2:[],day3:[],day4:[],day5:[],day6:[],day7:[]}
var reduce = function(obj, prev) {
// prev is basically the same as initial (except with whatever is added)
var day = obj.date.slice(0,-10) // figure out day, however it works
prev["day" + day].push(obj) // create grouped arrays
// you could also do something here to sort by _id
// which is probably also going to get you the latest for that day
// and use it to replace the last item in the prev["day" + 1] array if
// it's > that the previous _id, which could simplify things later
}
this.collection.group(keys, condition, initial, reduce, function(err, results) {
// console.log(results)
var days = results // it may be a property, can't remember
var lastDays = {}
days.forEach(function(day) {
// sort each day array and grab last element
lastDays[day] = days[day].sort(function(a, b) {
return a.date - b.date // check sort syntax, you may need a diff sort function if it's a string
}).slice(-1) // i think that will give you the last one
})
cb(lastDays) // your stuff
})
}
我的博客中的组和 map reduce 之间的更多比较:
http://j-query.blogspot.com/2011/06/mongodb-performance-group-vs-find-vs.html
本机驱动程序中没有关于 group 命令的文档,因此您必须在此处查看源代码:
https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js
也用于排序,请检查https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort 以了解确切的语法
编辑:更好的主意!!!
只需有一个名为“lastRequestOfDay”的特殊集合并将_id 设为当天。
用每个新请求覆盖该值。它将非常容易查询和快速编写,并且每天都会写入最后一个值!