Search code examples
mongodbmongodb-atlasmongodb-atlas-search

How to apply a filter, before running MongoDB Atlas full text search?


According to the documentation about Atlas Search, it states:

$search must be the first stage of any pipeline it appears in.

Well if that is the case, how do you apply Mongo filters. It seems very counter-intuitive to apply these filters on the output of the search?

We are thinking about using Mongodb full text search as an alternative to Algolia, but this limitation seems weird 🧐

Current pipeline:

const pipeline = [
    {
        $search: {
            text: {
                query,
                path: fields,
                fuzzy: {
                    maxEdits: 1,
                    maxExpansions: 50,
                },
            },
        },
    },
    {
        $match: {
            someField: 1,
        },
    },
];

Solution

  • In this case, it may be better to index someField in Atlas Search as a number, as it supports numeric types using the range operator and compound to combine the results. Since the entire query is run in Lucene, it should return results quicker.

    const pipeline = [
        {
            $search: {
                compound: {
                    should: {
                        text: {
                            query,
                            path: fields,
                            fuzzy: {
                                maxEdits: 1,
                                maxExpansions: 50,
                            },
                        },
                    },
                    filter: {
                        range: { 
                            path: "someField",
                            lte: 1,
                            gte: 1
                        }
                    }
                }
    
            }
        }
    ];