How to get all the values that contains part of a string using Mongoose find?

Sometimes, we want to get all the values that contains part of a string using Mongoose find.

In this article, we’ll look at how to get all the values that contains part of a string using Mongoose find.

How to get all the values that contains part of a string using Mongoose find?

To get all the values that contains part of a string using Mongoose find, we can use the $regex operator.

For instance, we write

Books.find({
    "authors": {
      "$regex": "Alex",
      "$options": "i"
    }
  },
  (err, docs) => {}
);

to call Books.find to query for authors set to a string that has 'Alex' in it anywhere in the string.

We set $options to 'i' to compare authors in a case-insensitive manner.

Conclusion

To get all the values that contains part of a string using Mongoose find, we can use the $regex operator.