##文档
{
"_id": ObjectId("53c4190a4572483830000053"),
"sendfrom": "joy",
"sendto": "iphone",
"sendtitle": "新趋势",
"user": "han",
"create_at": ISODate("2014-07-14T17: 53: 14.499Z")
}
文档是这样的要我如何使用聚合函数Aggregation 根据日期来分组啊 请大神指导,指导。谢谢啦。
最后采用方式:
Sendinfo.getallday = function(user, callback) {
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var group={
// key: {user:1,create_at:1},
keyf: function(sendinfos) {
var date = new Date(sendinfos.create_at);
var dateKey = (date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+'';
return {'day':dateKey,'user':sendinfos.user};//返回值
},//格式化日期
cond: {'user':user}, //查询条件 cond: {'user':user, 'create_at': { $gt:firstDay,$lt:lastDay}}, //查询条件
initial: {count:0}, //初始值
reduce: function(obj, prev) {prev.count++;},
finalize:{}
};
SendinfoModel.collection.group(
group.keyf,
group.cond, //查询条件
group.initial, //初始值
group.reduce,
group.finalize,
true,//reduce
function(err,sendinfos){
if (err) {
return callback(err);
}
console.log("new Date(1):"+new Date().setDate(1)+",new Date(31):"+new Date().setDate(31)+","+sendinfos);
callback(null,sendinfos);
}
);
};
13 回复
function map(){
var date = this.create_at; var year = date.getUTCFullYear(); var month = date.getUTCMonth(); month = month + 1; var day = date.getUTCDate();
var dateStr = year + "-" + month + "-" + day;
emit(dateStr, this);
} function reduce(key, values){ return {date:key, values:values}; } db.xxx.mapReduce(map, reduce, {out:"xxx_map_reduce"})