You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询无匹配日期时返回0的实现方法

MongoDB聚合查询:指定日期订单数统计(无数据返回0)

需求说明

接收用户输入的日期范围,统计对应时间段内已验证(verified:1)的订单数量;当该日期范围内无匹配数据时,返回count:0的结果,适配Redash可视化需求。

修改后的聚合查询代码

{
  "collection": "orders",
  "aggregate": [
    {
      "$match": {
        "verified": 1,
        "dateCreated": {
          "$gt": { "$humanTime": "{{ Date.start }} 00:00" },
          "$lt": { "$humanTime": "{{ Date.end }} 00:00" }
        }
      }
    },
    {
      "$group": {
        "_id": {
          "$dateToString": {
            "format": "%Y-%m",
            "date": "$dateCreated"
          }
        },
        "count": { "$sum": 1 }
      }
    },
    {
      "$sort": { "_id": -1 }
    },
    {
      "$facet": {
        "results": []
      }
    },
    {
      "$project": {
        "final": {
          "$cond": {
            "if": { "$eq": [{ "$size": "$results" }, 0] },
            "then": [{ "_id": "{{ Date.start }}", "count": 0 }],
            "else": "$results"
          }
        }
      }
    },
    { "$unwind": "$final" },
    { "$replaceRoot": { "newRoot": "$final" } }
  ]
}

关键修改说明

  1. 空结果处理逻辑:

    • 用$facet将统计结果存入results数组,方便判断是否为空。
    • 通过$cond和$size检查数组长度:无匹配数据时生成包含count:0的默认文档,否则保留原统计结果。
    • 最后用$unwind和$replaceRoot将结果转为Redash可直接可视化的格式。
  2. Redash参数适配:

    • 保留{{ Date.start }}和{{ Date.end }}作为Redash日期输入参数,确保用户输入的日期能正确代入查询。
    • $humanTime是Redash针对MongoDB查询的扩展语法,自动将字符串日期转为MongoDB可识别的日期类型。
  3. 日期格式调整:

    • 若需按日统计,只需将$dateToString的format改为%Y-%m-%d,同时调整$match的结束边界为{{ Date.start }} 23:59:59即可。

内容的提问来源于stack exchange,提问作者Mohamed Wahba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:55:20