node.js - 我想计算nodejs mongodb列中的三个字段,并且需要按月对其进行分组

标签 node.js arrays mongodb mongodb-query aggregation-framework

Sample Data Set

我想计算每个月的绿色、红色、琥珀色数量(即:按月分组),如下例所示:

{_id:2,Green:20,Red:12,Amber:23}

说_id代表月份(2:Feb)

注意:- 我正在从 mongodb 检索数据,并且日期列采用 ISO 日期类型格式

有人可以帮助我吗?

最佳答案

演示 - https://mongoplayground.net/p/0N7b2uNZJNL

db.collection.aggregate({
  "$project": {
    color: 1,
    month: {
      "$substr": [ "$date", 0, { "$indexOfCP": [ "$date", "/" ] } // extract month from date string
      ]
    }
  }
},
{
  "$group": {
    "_id": {  month: "$month", color: "$color" },
    "count": { "$sum": 1 }
  }
},
{
  "$project": {
    month: "$_id.month",
    details: [ { color: "$_id.color", count: "$count" } ] // add color count to the array
  }
},
{
  $project: {
    _id: 0,
    month: 1,
    color: {
      $arrayToObject: { // get object from array like green: 1
        $map: {
          input: "$details", as: "pair", in: [ "$$pair.color",  "$$pair.count" ]
        }
      }
    }
  }
},
{
  "$group": {
    "_id": "$month",
    "color": { "$mergeObjects": "$color" } // merge all the colors
  }
},
{
  $replaceWith: {
    $mergeObjects: [ {  _id: "$_id"  }, "$color" ] // bring color out of the object
  }
})

$substr

$indexOfCP

$arrayToObject

$mergeObjects

$replaceWith

关于node.js - 我想计算nodejs mongodb列中的三个字段,并且需要按月对其进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66804477/

相关文章:

javascript - 将变量与自身进行比较

arrays - 创建 SCNNode 数组时出错

javascript - 如何使 if/else 语句评估所有变量

javascript - 如何使用位置插入 MongoDB 集合

javascript - Mongoose - 如何确定查询中是否已存在嵌套对象?

node.js - Nodejs Telegram 机器人消息收到轮询错误

javascript - 无法从 User.js 中找到方法

javascript - 为什么我的 crypto.createHmac() 会为相同的输入生成不同的 HMAC?

javascript - Node.js 和 CPU 密集型请求

mongodb - 如何使用 mongodb 更新包含在父对象数组中的对象的属性?