Querying with Regexes
In the last step, you learned how to query for documents that match a specific value. In this step, you'll learn how to query for documents that match a pattern.
This is similar to doing a LIKE
query in SQL.
Edit the regex endpoint
In the server/index.mjs
file, you will notice another app.get
line for the url /regex/:name
. This is where we'll add the code to query by regex.
Using the almost same code you used in the previous step, add the code needed to query the data using a regex. To do so, you need to change the value passed in the query to a regular expression rather than the parameter directly.
Answer
app.get("/regex/:name", async (req, res) => {
const players = await collection
.find({ short_name: new RegExp(req.params.name, "i") })
.toArray();
res.json(players).status(200);
});
Test it out
Try it out. In the client, change the dropdown to regex
, and type in a partial name. You should see the results filtered by the regex.
Problems with this approach
This approach works, but it's not ideal. The reason is that it's not very efficient. The reason is that it has to scan the entire collection to find the matches. This is because the regex is not indexed.
That doesn't mean you should never use regexes to query. If you have a small collection, it's not a big deal. But if you have a large collection, it can be a problem.
A good use case for a regex is when you want to match documents starting with a certain string. For example, if you wanted to find all players whose name starts with "A", you could use the regex /^A/
. This would be a good use case for a regex as it can still leverage the index on the short_name
field.