Search code examples
mongodb-atlas-search

MongoDB full text search, autocomplete on two fields


I am trying to implement MongoDB atlas search, and the objective is autocomplete on 2 fields.

I currently have this implementation:

const searchStep = {
    $search: {
        // Read more about compound here:
        // https://docs.atlas.mongodb.com/reference/atlas-search/compound/
        compound: {
            must: [
                {
                    autocomplete: {
                        query,
                        path: 'name',
                    },
                },
                {
                    autocomplete: {
                        query,
                        path: 'description',
                    },
                },
            ],
        },
    },
}

This does not seem to work, seems to only work when there is both a match on the name AND description. How can I fix this, so I query for both name and description?

I now tried using the wildcard option:

{
    wildcard: {
        query,
        path: ['name', 'description'],
        allowAnalyzedField: true,
    }
}

But the wildcard solution does not seem to work - no relevant results are returned...


Solution

  • If you are trying to match on name or subscription, use should: instead of must:

    must will require that all of the subqueries match, where as should requires that only 1 of them does.

    const searchStep = {
        $search: {
            // Read more about compound here:
            // https://docs.atlas.mongodb.com/reference/atlas-search/compound/
            compound: {
                should: [
                    {
                        autocomplete: {
                            query,
                            path: 'name',
                        },
                    },
                    {
                        autocomplete: {
                            query,
                            path: 'description',
                        },
                    },
                ],
            },
        },
    }