skip to Main Content

The following statement regarding range filter and sorting and the way the predicates had to be placed is confusing.

"MongoDB cannot do an index sort on the results of a range filter. Place the range filter after the sort predicate so MongoDB can use a non-blocking index sort."

How can we place a filter after a sort predicate in a mongo query such as below

db.collectionName.find({}).sort(sortField:1);

https://www.mongodb.com/docs/upcoming/tutorial/equality-sort-range-rule/#range

2

Answers


  1. I think you may be misunderstanding what the "placement" is referring to.

    The ESR guidance is about how to define the index itself, specifically what order the keys should be listed in. It has nothing to do with rearranging anything in the query itself. Indeed you cannot do something like

    .find({}).sort({sortField:1}).find({rangeCondition:{$gte:1}})
    

    Instead your query may look something like this:

    .find({rangeCondition:{$gte:1}}).sort({sortField:1})
    

    And you would therefore create your index as:

    .createIndex({sortField:1, rangeCondition:1})
    

    This is as opposed to creating the index with the fields reversed, e.g. .createIndex({rangeCondition:1, sortField:1 }).

    Note also that this just provides general guidance that is not appropriate in all situations. If your range predicates are sufficiently selective, then you may achieve better results by having the index lead with that field instead.

    Login or Signup to reply.
  2. You Can use the aggregation framework:

    • Use the $sort stage to sort the documents based on the desired field.
    • Use the $match stage to apply the filter after sorting.
      Here’s an example using the aggregation framework:
    db.collectionName.aggregate([
      { $sort: { sortField: 1 } }, // Sort the documents based on sortField
      { $match: { /* Your filter criteria */ } } // Apply the filter after sorting
    ]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search