Need to filter on a number (exact) and avoid using $match

As the doc says here : https://docs.atlas.mongodb.com/atlas-search/performance/#-match-aggregation-stage-usage

It’s not recommanded to use a $match in a $search query because it can drastically slow down query results.

In my case, I need to filter on a number field so I am using a compound search like this :

db.getCollection("movies").aggregate(
[
    {
        $search: {
            "index":"year",
            "compound": {
                "must": [{
                  "text": {
                    "query": "war",
                    "path": "plot"
                  }
                }],
                
                "filter": [{
                  "range": {
                    "path": "year",
                    "gte": 1980,
                    "lte":1980
                  }
                }]
              }
        }
    },
    {
        $project: {"title":1,"year":1,"countries":1,"plot":1}
    }
]

As you can see I want to filter my movies released only in 1980, so I’am using a range filter with gte=lte=1980.

It’s the only way I found to do this without using a $match stage (that ideed, decreases the perf), but I think this is not very elegant.

Is there another way ?

Thank you.

1 Like

Hi there, PM from Atlas Search here! This query looks great to me! You could also use Equals in place of the range.

That’s not what’s written in the docs :

The equals operator supports querying boolean and objectId values.

Here, I want to query a number field. If I replace range with equals it crashes.

Right, that is my mistake, I glazed over that limitation. In that case the way you have it written is good.

Feel free to vote for this as a feature if that is interesting to you: The equals operator should support numeric datatypes – MongoDB Feedback Engine

We are considering it in the near future.

1 Like