且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 mongoose.js 按月和年分组

更新时间:2023-01-29 21:51:24

Mongoose 为 MongoDB 聚合框架提供了一个轻量级的包装器.如果您不熟悉聚合,您可以从 MongoDB 文档中了解更多信息:http://docs.mongodb.org/手动/聚合/

Mongoose provides a lightweight wrapper around the MongoDB aggregation framework. If you're new to aggregation, you can learn more about in from the MongoDB docs: http://docs.mongodb.org/manual/aggregation/

要将您的数据整理成上述形式,您可以使用聚合管道和一系列 $group 操作.这里使用的是 mongoose 框架:

To massage your data into the form you've described above, you can use an aggregation pipeline with a series of $group operations. Here it is using the mongoose framework:

var dateSchema = mongoose.Schema({…});
var DateItem = mongoose.model('DateItem', dateSchema);

DateItem.aggregate(
      { $group : { 
           _id : { year: { $year : "$accessDate" }, month: { $month : "$accessDate" },day: { $dayOfMonth : "$accessDate" }}, 
           count : { $sum : 1 }}
           }, 
      { $group : { 
           _id : { year: "$_id.year", month: "$_id.month" }, 
           dailyusage: { $push: { day: "$_id.day", count: "$count" }}}
           }, 
      { $group : { 
           _id : { year: "$_id.year" }, 
           monthlyusage: { $push: { month: "$_id.month", dailyusage: "$dailyusage" }}}
           }, 
      function (err, res)
           { if (err) ; // TODO handle error 
             console.log(res); 
           });
});

第一个 $group 将产生这种形式的文档,每天一个:

The first $group will result in documents of this form, one for each day:

{ 
  "_id" : { "year" : 2013, "month" : 8, "day" : 15 },
  "count" : 1
}

第二个 $group 将生成按月分组的文档:

The second $group will result in documents grouped by month:

{
  "_id" : { "year" : 2012, "month" : 11 },
 "dailyusage" : [
          { "day" : 6, "count" : 1 },
          { "day" : 9, "count" : 1 },
          ... ]
},

第三个 $group 将产生更大的文档,每年一个.

And the third $group will result in even larger documents, one for each year.

此查询会将您的数据聚合到大型分层文档中.但是,如果您计划在聚合后对此数据运行查询,那么这可能不是最有用的数据形式.请考虑如何使用聚合数据.包含更多较小文档的架构,可能每月一个,甚至每天一个,可能会更方便.

This query will aggregate your data into large, hierarchical documents. If you plan to run queries on this data after aggregation, however, this might not be the most useful form for your data to be in. Consider how you'll be using the aggregated data. A schema involving more smaller documents, perhaps one per month or even one per day, might be more convenient.