MongoDB 中每年和每月的聚合 [英] Aggregation per year and month in MongoDB

查看:32
本文介绍了MongoDB 中每年和每月的聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:我有一个数组名称作为代码,我有一个查询参数名称作为year(下拉列表 2016,2017,2018,2019,....) 和 month 下拉列表为 (ALL,01,02,03,04,05,06,07,08,09,10,11,12).

Explanation: I have an Array name as code, I have query parameters name as year(drop-down list 2016,2017,2018,2019,....) and month drop-down list as (ALL,01,02,03,04,05,06,07,08,09,10,11,12).

CASE1:如果用户选择特定年份和特定月份,则相应地获取code 数组.

CASE1: If the user selects a specific year and specific month get the code array accordingly.

CASE2:如果用户选择特定年份和月份ALL,则获取code数组完整年份.

CASE2: If the user selects the specific year and from month ALL, get the code array complete year.

{
  "code":[
    {
      "k": "2016-06-18T18",
      "v": 1
    },
    {
      "k": "2016-06-18T21",
      "v": 2
    },
    {
      "k": "2016-07-19T00",
      "v": 13
    },
    {
      "k": "2015-06-19T03",
      "v": 6
    },
    {
      "k": "2015-07-19T06",
      "v": 6
    }
  ]
}

CASE 1 Expected Output IF user-selected : From year drop-down : 2016 , month : 06

CASE 1 Expected Output IF user-selected : From year drop-down : 2016 , month : 06

{
  "code":[
    {
      "k": "2016-06-18T18",
      "v": 1
    },
    {
      "k": "2016-06-18T21",
      "v": 2
    }
  ]
}

如果用户选择的情况 2 预期输出:从年份下拉列表:2016 年,月份:所有.

CASE 2 Expected Output IF user-selected : From year drop-down : 2016 , month : ALL.

{
  "code":[
    {
      "k": "2016-06-18T18",
      "v": 1
    },
    {
      "k": "2016-06-18T21",
      "v": 2
    },
    {
      "k": "2016-07-19T00",
      "v": 13
    },
  ]
}

推荐答案

  • 初始化请求参数
  • var year = req.year;
    var month = req.month;
    

    • 设置默认年份条件
    • var condition = [{
        $eq: [{ $substr: ["$$this.k", 0, 4] }, String(year)]
      }];
      

      • 检查月份是否可用,而不是全部,然后添加条件
      • if (month && month != "all") {
          condition.push({
            $eq: [{ $substr: ["$$this.k", 5, 2] }, String(month)] 
          });
        }
        

        • $filter 迭代代码循环并过滤以上准备好的条件
          • $filter to iterate loop of code and filter above prepared conditions
          • db.collection.aggregate([
              {
                $set: {
                  code: {
                    $filter: {
                      input: "$code",
                      cond: { $and: condition }
                    }
                  }
                }
              }
            ])
            

            游乐场

            这篇关于MongoDB 中每年和每月的聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆