In Mongoose, you can use the $regex
operator to perform a search query in MongoDB, similar to SQL LIKE
statement.
MongoDB uses regular expressions for pattern matching that is more powerful than SQL LIKE
statement. Regular expressions allow you to create any search pattern that you can imagine.
Here is an example that finds documents containing a specific string:
const mongoose = require('mongoose')
const User = mongoose.model('User', { name: String })
const users = await User.find({ name: { $regex: /john/i } })
Note that the i
in the above query indicates case in-sensitive match. You can also pass a RegExp
object instead of $regex
operator:
const users = await User.find({ name: new RegExp('john', 'i') })
To match a field that starts with a specific string, you can use the following query:
const users = await User.find({ name: { $regex: /^john/i } })
Similarly, to find documents that end with a specific string, use the following query:
const users = await User.find({ name: { $regex: /john$/i } })
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.