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

MongoDB Shell与PyMongo聚合排序结果不一致问题排查

Why does the same aggregation sort differently in Mongo Shell vs PyMongo?

This is almost certainly due to dictionary ordering behavior in older Python versions (pre-3.6) breaking the sort order you defined. Here's the breakdown:

  • In Mongo Shell, JSON objects preserve the order of keys. When you specify { "_id.category": 1, "count": -1 } as your sort stage, MongoDB executes the sort exactly in that order: first ascending by _id.category, then descending by count.
  • But in Python versions before 3.6, regular dictionaries do not preserve insertion order. When you define your sort stage as a standard Python dict, the order of the keys might get rearranged (e.g., count could end up being processed first by MongoDB). This means the sort would prioritize count over _id.category, making it look like only the count is being sorted on.

Fixes to resolve this:

  1. Upgrade to Python 3.6+: Starting with Python 3.6, regular dictionaries maintain insertion order, so your existing pipeline will work as expected without changes.
  2. Use collections.OrderedDict for the sort stage: If you can't upgrade Python, explicitly enforce the key order using OrderedDict:
    from collections import OrderedDict
    
    pipeline = [
        { "$unwind" : "$calls" },
        { "$group": { "_id": {"category": "$calls.category","api": "$calls.api"},"count": { "$sum": 1} } },
        { "$sort": OrderedDict([("_id.category", 1), ("count", -1)]) }
    ]
    output = list(db.DynamicData.aggregate(pipeline, allowDiskUse=True))
    
  3. Verify the pipeline being sent: You can print the pipeline before executing it to confirm the sort key order is correct. For older Python versions, the standard dict might show the keys in a different order than you wrote them.

One quick sanity check: Make sure both the Mongo Shell and PyMongo are connecting to the exact same database/collection with identical data—though this is less likely to be the issue here given your description.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:21:29