MongoDB: How to Query with “Like” Regex


You can use the following methods to perform a query in MongoDB with “like” regex:

Method 1: Find Documents that Contain String

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

Note that the i indicates a case-insensitive match.

Method 2: Find Documents that Start with String

db.collection.find({name: {$regex : /^string/i}}) 

Method 3: Find Documents that End with String

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

The following examples show how to use each method 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: Find Documents that Contain String

We can use the following code to find all documents that contain the string ‘avs’ in the team field:

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

This query returns the following two documents:

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

{ _id: ObjectId("618285361a42e92ac9ccd2c6"),
  team: 'Cavs',
  position: 'Guard',
  points: 33 }

Example 2: Find Documents that Start with String

We can use the following code to find all documents that start with the string ‘gua’ in the position field:

db.teams.find({position: {$regex : /^gua/i}})

This query returns the following three documents:

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

{ _id: ObjectId("6180504e8ffcfe76d07b1da7"),
  team: 'Spurs',
  position: 'Guard',
  points: 22 }

{ _id: ObjectId("618285361a42e92ac9ccd2c6"),
  team: 'Cavs',
  position: 'Guard',
  points: 33 }

Example 3: Find Documents that End with String

We can use the following code to find all documents that end with the string ‘ward’ in the position field:

db.teams.find({position: {$regex : /ward$/i}})

This query returns the following document:

{ _id: ObjectId("618050808ffcfe76d07b1dab"),
  team: 'Warriors',
  position: 'Forward',
  points: 26 }

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

Leave a Reply

Your email address will not be published.