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

MongoDB近30天过滤后聚合分组返回空数组问题

问题解决:聚合管道时间过滤后分组结果为空

你的问题出在聚合管道的$match阶段写法错误:

  • filter_query本身已经是完整的查询条件{'load_date': {'$gte': start_date, '$lte': end_date}}
  • 但你在$match里额外嵌套了一层{'load_date': filter_query},这会让MongoDB尝试匹配不存在的load_date.load_date字段,导致没有数据进入后续的$group阶段,最终返回空数组

修正后的代码如下:

end_date = datetime.now()
start_date = end_date - timedelta(days=30)
filter_query = {
    'load_date': {
        '$gte': start_date,
        '$lte': end_date
    }
}

count = await collection.count_documents(filter_query)
print(count) # gives correct count

# 修正$match阶段,直接使用filter_query
pipeline = [
    {'$match': filter_query}, 
    {'$group': {'_id': '$category', 'count': {'$sum': 1}}}
]
items = collection.aggregate(pipeline)
category = await items.to_list(limit)

return {"total_items": count, "items": category}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:12:45