【问题标题】:how to group data based on months in nodejs?如何在nodejs中根据月份对数据进行分组?
【发布时间】:2016-10-10 23:30:12
【问题描述】:
Sale.aggregate({
  $match: filter
}, {
  $group: {
    "_id": {
      "store_id": "$store_id",
      //"created_on": { $dateToString: { format: "%Y-%m-%d", date: "$strBillDate" } }
    },
    month: {
      $month: "$strBillDate"
    },
    store_id: {
      $first: "$store_id"
    },
    strBillAmt: {
      $sum: "$strBillAmt"
    },
    strBillNumber: {
      $sum: 1
    }
  }
})

我需要按月分组销售额,而不是日期,nodejs中如何按月分组销售额

【问题讨论】:

  • 显示你的数据库结构。
  • store_id: {type: String }, strBillNumber: {type: String },strBillDate: {type: Date },strBillAmt: {type: Number },

标签: node.js mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

我首先在聚合链中使用projection 来提取月度和年度值,然后进行分组:

<doc-name>.aggregate([
    { $project:
        { _id: 1,
          year: { $year: "$date" },
          month: { $month: "$date"},
          amount: 1
        }
    },
    { $group:
        { _id: { year: "$year", month: "$month" },
          sum: { $sum: "$amount" }
        } 
    }])

我也试过你的模型:

var testSchema = mongoose.Schema({
  store_id: { type: String },
  strBillNumber: { type: String },
  strBillDate: { type: Date },
  strBillAmt: { type: Number }
});

var Test = mongoose.model("Test", testSchema);

创建一些测试数据:

var test = new Test({
  store_id: "1",
  strBillNumber: "123",
  strBillDate: new Date("2016-04-02"),
  strBillAmt: 25
});
var test2 = new Test({
  store_id: "1",
  strBillNumber: "124",
  strBillDate: new Date("2016-04-01"),
  strBillAmt: 41
});
var test3 = new Test({
  store_id: "3",
  strBillNumber: "125",
  strBillDate: new Date("2016-05-13"),
  strBillAmt: 77
});

运行查询:

Test.aggregate([
    { $project:
        { store_id: 1,
            yearBillDate: { $year: "$strBillDate" },
            monthBillDate: { $month: "$strBillDate" },
            strBillAmt: 1
        }
    },
    { $group:
        { _id: {yearBillDate: "$yearBillDate", monthBillDate:"$monthBillDate"},
          sum: { $sum: "$strBillAmt" }
        }
    }
    ], function(err, result) {
        console.log(err, result)});

并得到了合理的结果:

【讨论】:

  • 您的数据模型是否出错或无法正常工作?
  • 我再次尝试使用您提供的架构并编辑我的帖子以支持您的数据。如果有帮助,请看看。
猜你喜欢
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 2018-12-31
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
相关资源
最近更新 更多