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 bycount. - 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.,
countcould end up being processed first by MongoDB). This means the sort would prioritizecountover_id.category, making it look like only the count is being sorted on.
Fixes to resolve this:
- 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.
- Use
collections.OrderedDictfor the sort stage: If you can't upgrade Python, explicitly enforce the key order usingOrderedDict: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)) - 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
相关产品推荐
相关产品推荐

