Home:ALL Converter>Why should the $search be the first in pipeline stages in mongoDB?

Why should the $search be the first in pipeline stages in mongoDB?

Ask Time:2021-11-27T23:16:47         Author:moemous

Json Formatter

This is my code which searches the whole collection and returns the documents that the value of their name fields are either Dexter or Prison Break or Breaking bad. Why should $search be at the top of stages; otherwise, I will get an error. Plus, I read on MongoDB doc that "The $match stage that includes a $text must be the first stage in the pipeline." Here

 app.get('/', (req, res) => {
      db.collection('subs')

      .aggregate([
      { $match: { $text: { $search: 'honey' } } },
      { $match: { name: { $in: ['Dexter', 'Prison Break', 'Breaking Bad'] } } },
    ])

    .toArray((err, result) => {
      if (err) {
        throw new err();
      }
      res.json({
        length: result.length,
        body: { result },
      });
    });
});

I suppose the second line which filters the documents based on their name should come first; in order to reduce time and get a quick result because in this case, MongoDB will not have to search the whole collection and just search a few documents and returns the result. why is that? is there any way for optimization?

Author:moemous,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70136053/why-should-the-search-be-the-first-in-pipeline-stages-in-mongodb
yy