How to sort mongodb with pymongo

前端 未结 7 1845
情书的邮戳
情书的邮戳 2020-11-28 04:01

I\'m trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows:



        
7条回答
  •  日久生厌
    2020-11-28 04:45

    TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().

    Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:

    1. Using .find() and .sort().
    2. Or using the aggregation pipeline.

    As suggested by many .find().sort() is the simplest way to perform the sorting.

    .sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])
    

    However, this is a slow process compared to the aggregation pipeline.

    Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:

    1. $match (optional step)
    2. $sort

    NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.

    Here's an example of the aggregation pipeline.

    db.collection_name.aggregate([{
        "$match": {
            # your query - optional step
        }
    },
    {
        "$sort": {
            "field_1": pymongo.ASCENDING,
            "field_2": pymongo.DESCENDING,
            ....
        }
    }])
    

    Try this method yourself, compare the speed and let me know about this in the comments.

    Edit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.

提交回复
热议问题