Skip to content

Latest commit

 

History

History

4-sorting

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Sorting using the near operator

As documented here, using a $sort aggregation pipeline stage after a $search stage can drastically slow down query results. We have this UserVoice request open for improving sort performance with Atlas Search. Meanwhile, we recommend using the Atlas Search near operator to sort documents based on a numeric, date, or geo field. This example demonstrates how the near operator can be used to return documents in a sorted order, and without using a separate $sort stage. Specifically, it shows how to perform a descending sort on the field “B”, for the documents where the field “A” contains the string “Adam”. By changing the "origin" the sort order can be changed.

Code Example

{
  $search: {
    "compound": {
      "must": [{
        "text": {
          "query": "Adam",
          "path": "A"
        }
      }, {
        "range": {
          "gt": 0,
          "lt": 12,
          "path": "B"
        }
      }, {
        "near": {
          "path": "B",
          "origin": 12,
          "pivot": 1
        }
      }]
    }
  }
}

Author(s)

Harshad Dhavale

References

Docs: https://docs.atlas.mongodb.com/reference/atlas-search/near/