如何在Mongoose / NodeJS的时间戳字段中计数不同的date项目?

我在我的NodeJS中使用Mongoose,并且有一个文档看起来像这样的集合 –

var SomeSchema = new Schema({ date: { type: Date, default: new Date() }, some_item: { type: String } }); 

date字段包含时间部分的date(例如, 2014-05-09 09:43:02.478Z )。 2014-05-08如何获得给定date的不同项目数?

编辑:理想情况下,我想获得每个不同date的logging计数。

你想要的是使用aggregate()命令的聚合框架,至less在你问的时候find一个date:

 SomeSchema.aggregate( [ { "$match": { "date": { "$gte": new Date("2014-05-08"), "$lt": new Date("2014-05-09") } }}, { "$group": { "_id": "$some_item", "count": { "$sum": 1 } }} ], function(err,result) { // do something with result } ); 

如果你正在寻找“计数”在几个date,那么你可以做这样的事情:

 SomeSchema.aggregate( [ { "$match": { "date": { "$gte": new Date("2014-05-01"), "$lt": new Date("2014-06-01") } }}, { "$group": { "_id": { "year": { "$year": "$date" }, "month": { "$month": "$date" }, "day": { "$dayOfMonth": "$date" } } "count": { "$sum": 1 } }} ], function(err,result) { // do something with result } ); 

这给你“每天”分组。 如果您希望进一步了解,请在文档中查找date聚合操作符 。