【问题标题】:MongoDB: Match on multiple but do not include duplicatesMongoDB:匹配多个但不包含重复项
【发布时间】:2021-08-25 23:57:46
【问题描述】:

我正在编写一个查询匹配跨越两年的几个月范围内的文档。之后我想在另一个字段上使用聚合函数,但不想避免重复。例如,我想合计从 2020 年开始到 2021 年结束的 10 月到 8 月的两个字段。如何在我的合计中排除 2020 年 1 月到 8 月的月份?到目前为止,我有以下代码。

[{
    $match: {
        "Calendar Year": {
            $in: [2020, 2021]
        },
        "Month": {
            $in: ["Oct", "Nov", "Dec", "Jan",
                "Feb", "Mar", "Apr", "May", "Jun",
                "Jul", "Aug"
            ]
        }
    }
}, {
    '$group': {
            '_id': {
                'Month': '$Month', 
                'Facility': '$Facility'
            }, 
            'Gal_Treated': {
                '$sum': '$MGal Treated'
            }, 
            'Cr_Mass_tot': {
                '$sum': '$Chrome (kg)'
            }
        }
    }

}]

示例数据结构文档:

_id:6126a7afe24933f84da03a7f
Calendar Year:1991
Fiscal Year:1991
Quarter:4
Month:"Sep"
Facility:"SVE (A)"
Total mass (kg):140
Carbon Tet (kg):140

预期回报:

_id:Object
MGal_treated:248.5
Cr_mass_treated:11.0

谢谢!

【问题讨论】:

  • 您能否提供一些测试数据模型并展示预期结果。
  • 于婷 测试数据模型及预期结果见更新帖。

标签: mongodb aggregate grouping partitioning


【解决方案1】:

您可以将$cond添加到$sum中,并将您的condition添加到if

'$sum':{
            $cond: { 
                if: { 
                    $and: [
                    { "Month": { "$in", ["Jan","Feb", "Mar", "Apr", 
                                         "May", "Jun", "Jul", "Aug" ] } }, 
                    { "Calendar Year": "2020" ] }]}, 
                then: '$Chrome (kg)', 
                else: NumberInt(0) 
           }
       }

【讨论】:

  • 由于“月份”字段是字符串,$gte 和 $lte 是否仍然有效?
  • 我改了答案,用$in代替gtelte
猜你喜欢
  • 2015-01-22
  • 2013-11-26
  • 1970-01-01
  • 2018-08-06
  • 2019-01-17
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多