I'm building a web app using Node and MongoDB Atlas. I need to implement a search bar, which will be used to search a MongoDB collection in 2 particular fields. I was doing some research on the best way to build this, but the Mongo docs are slightly confusing.
These docs for Atlas Search mention a $search
aggregation stage. On the other hand, these docs for MongoDB Aggregation Stages have no mention of the $search
stage at all.
I want the search to be 'fuzzy', and this answer says this should be done using the regex, but I couldn't find any reference for a $regex
operator in the Atlas Search docs. For a previous task, I created an aggregation pipeline in which I used the $match
operator with db.collection.aggregate()
. It seems to me that the $match
operator should work just fine for the fuzzy search bar as well, since it would allow me to use the $regex
operator. I believe $match
can also take advantage of any indexes you might create on Atlas for your queries.
So my question is basically this - What's the difference between using $search
and $match
? Does one offer performance/cost benefits over the other? Or are they for different use cases which I'm totally missing? If using $search
is the way to go, how would one make the query such that it's fuzzy? I will be grateful for any help.
$search
is the best option for implementing search functionality. It will produce more accurate results, it will offer features like highlighting and autocomplete, and will be more performant for this use case.
As you work through the implementation, here are the docs.
Here is what a simple query with fuzzy matching will look like, with the defaults for the fuzzy setting:
{
$search: {
"index": <index name>, // optional, defaults to "default"
"text": {
"query": "queryText",
"path": "<fields-to-search>",
"fuzzy": {
"maxEdits": 2
}
}
}
}