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
相关产品推荐
相关产品推荐

