Lesson 5: $search operators: near and range / Learn

Code Summary: $search operators: near and range

Use the near Operator

The near operator performs a search for dates, numbers, or geographic locations nearest to a given value or point. In the following example, the near operator is used with plotReleasedIndex to search for movies released around May 17, 1999.

db.movies.aggregate([
   {
      "$search": {
         "index": "plotReleasedIndex",
         "near": {
            "path": "released",
            "origin": ISODate("1999-05-17T00:00:00.000+00:00"),
            "pivot": 2629746000
         }
      }
   },
{ "$project": { "_id": 0, "title": 1, "released": 1, "score": { "$meta": "searchScore" }}}
])

Use the range Operator

The range operator performs a search based on a range of numbers or dates. The following example uses the range operator to return all documents with movies released between January 1st, 1994 and January 1st, 1999.

db.movies.aggregate([
  {
    "$search": {
      "index": "plotReleasedIndex",
      "range": {
        "path": "released",
        "gt": ISODate("1994-01-01T00:00:00.000Z"),
        "lt": ISODate("1999-01-01T00:00:00.000Z")
      }
    }
  },
  { "$project": { "_id": 0, "title": 1, "released": 1 }}
])