How to check if a field contains a string in MongoDB?

In MongoDB, we can use the $regex operator to check if a field contains a string. The $regex operator uses a regular expression to match the string in the specified field. For example, the following query will find any documents with a title field containing the string “MongoDB”: db.collection.find({title: {$regex: /MongoDB/}});


You can use the following syntax in MongoDB to check if a certain field contains a specific string:

db.collection.findOne({name: {$regex : /string/}})

The following examples show how to use this syntax with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})
db.teams.insertOne({team: "Warriors", position: "Forward", points: 26})
db.teams.insertOne({team: "Cavs", position: "Guard", points: 33})

Example 1: Check if Field Contains String

We can use the following code to check if there is any document that contains the string ‘avs’ in the team field:

db.teams.findOne({team: {$regex : /avs/}}) 

This query returns the following document:

{ _id: ObjectId("618050098ffcfe76d07b1da5"),
  team: 'Mavs',
  position: 'Guard',
  points: 31 }

Note that the function returns the first document in a collection that satisfies the query criteria.

This means that other teams may also have the string ‘avs’ in their team name, but the document containing the team name ‘Mavs’ was simply the first.

Example 2: Check if Field Contains String (Case-Insensitive)

We can also use an i after the string to perform a case-insensitive match.

For example, suppose we use the following query:

db.teams.findOne({team: {$regex : /AVS/i}}) 

This query also returns the following document:

{ _id: ObjectId("618050098ffcfe76d07b1da5"),
  team: 'Mavs',
  position: 'Guard',
  points: 31 }

Example 3: Check if Field Contains String (No Result)

If a field does not contain the specific string we searched for, we will simply receive null as a result.

For example, suppose we use the following query:

db.teams.findOne({team: {$regex : /ricks/}}) 

This query returns the following result:

null

Since no document contains the string ‘ricks’ in the team name, we receive null as a result.

Note: You can find the complete documentation for $regex .

The following tutorials explain how to perform other common operations in MongoDB:

x