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?