Home » MongoDB: How to Check if Field Contains a String

MongoDB: How to Check if Field Contains a String

by Tutor Aspire

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 findOne() 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 here.

Additional Resources

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

MongoDB: How to Query for “not null” in Specific Field
MongoDB: How to Query with “Like” Regex
MongoDB: How to Add a New Field in a Collection
MongoDB: How to Remove a Field from Every Document

You may also like