mongoose Regex Query

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Regular expression or Regex is a very important part of programming. It is usually used to find a pattern in a string. It takes time to understand regex and because of it being a bit tough, beginners usually skip this topic. This is always a mistake because the regular expression is used frequently in developing. In this article, we will discuss how to use mongoose regex query.

We will use the restaurant collections.

1
2
3
4
5
6
7
8
9
10
11
12
{ "_id" : ObjectId("5e2e86c8ee1f22706dac168f"), "dish" : "chicken burger", "price" : "5" }
{ "_id" : ObjectId("5e2e86e1ee1f22706dac1690"), "dish" : "bacon burger", "price" : "7" }
{ "_id" : ObjectId("5e2e8716ee1f22706dac1691"), "dish" : "bacon chicken pasta", "price" : "10" }
{ "_id" : ObjectId("5e2e8721ee1f22706dac1692"), "dish" : "noodles in chicken", "price" : "10" }
{ "_id" : ObjectId("5e2e8777ee1f22706dac1697"), "dish" : "chicken salad", "price" : "10" }
{ "_id" : ObjectId("5e2e8781ee1f22706dac1698"), "dish" : "bacon salad", "price" : "12" }
{ "_id" : ObjectId("5e2e8799ee1f22706dac1699"), "dish" : "tuna sandwich", "price" : "15" }
{ "_id" : ObjectId("5e2e87a4ee1f22706dac169a"), "dish" : "chicken sandwich", "price" : "12" }
{ "_id" : ObjectId("5e2e87dfee1f22706dac169b"), "dish" : "red sauce pasta", "price" : "5" }
{ "_id" : ObjectId("5e2e87efee1f22706dac169c"), "dish" : "red sauce chicken pasta", "price" : "10" }
{ "_id" : ObjectId("5e2e87f9ee1f22706dac169d"), "dish" : "red sauce bacon pasta", "price" : "12" }
{ "_id" : ObjectId("5e2e8810ee1f22706dac169e"), "dish" : "super veggie salad", "price" : "7" }

In each document, there is a field named dish. There are different types of dishes in this collection. Many of these are bacon dishes, such a bacon burger, bacon chicken pasta, bacon salad, etc. Now suppose we want all those dishes that contain bacon in them. We need to filter the result in such a way that each dish containing bacon in its name should be present. So we need to find a pattern in a string. This is where regex can be used.

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

regex in mongoose

Let’s create a route handler.

1
router.route("/find").get(function(req, res) {});

The above route handler will be invoked when the route ‘/find’ will be executed.

Now, we will add a find() method inside it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
router.route('/find').get(function(req,res){

    restuarant.find( {},function(err, result){

        if(err){
            res.send(err)
        }
        else{
            res.json(result)
        }



})

Normally, in a query part, we simply give the value that we want to match. But in the case of regex, we put the pattern in between two slashes(/). For bacon, we will do something like below.

1
{ "dish" : /bacon/}

This regex will match any dish that has “bacon” in it. It does not matter if the “bacon” comes in front, or middle, or at the last. Let’s execute it using the postman tool and see the results.

Image from Gyazo

Yes! It works perfectly.

The regular expression is a very vast topic. We can do a lot of things with it. Now suppose, we want all the dishes where the name begins with “bacon”, or where the name ends with “bacon”. To do this, we will use quantifiers.

So to find the dishes that begin with “bacon”, we will use ^ quantifier. Observe the following.

1
{ "dish" : /^bacon/

This means, the string should start with “bacon” and anything can follow it. Let’s add it to the route handler.

1
2
3
4
5
6
7
8
9
router.route("/find").get(function(req, res) {
  restaurant.find({ dish: /^bacon/ }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

We can see only those dishes are present in the result that begins with “bacon”. Similarly, we can also get those dishes that end with “bacon”. For this, we can use the $ quantifier. Well, we do not have any dish that ends with “bacon” in the restaurant collection. So, let’s find those dishes that ends with “salad”.

1
{ "dish" : /salad$/

This means the string should end with “salad”. Let’s add it to the route handler.

1
2
3
4
5
6
7
8
9
router.route("/find").get(function(req, res) {
  restaurant.find({ dish: /salad$/ }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Let’s execute this route using the postman tool.

Image from Gyazo

Yes! only those documents are present in the result where the dish ends with “salad”.

Conclusion

So this is how we can use regex in a query in mongoose. Regex can be used in various ways. Three of the most common ways are illustrated in this article.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.