How to Search for Text with Regex using the MongoDB Shell

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In this short step-by-step tutorial we’ll show you how to search for specific text within a collction of documents using regex or Regular Expressions. Regular Expressions are a super useful text pattern matching functionality that every programmer should be familiar with. The syntax is hard to remember but we hope this article will give you a simple example. We’ll show you how to search for a specific string in a collection step-by-step but if you’d just rather see the code, scroll to the bottom to see Just the Code.

Prerequisites

  • You should have MongoDB installed and running.
  • It’s recommended that you create a database and collection to experiment with as you follow along.
  • Some command line experience is recommended.

Goal

We always like to start out with an explicit goal to make sure we hit our mark by the end of the tutorial. To demonstrate searching for text within fields our goals is search for any mention of Object Rocket within our demoCommentsCollection in the demoDatabase. Here we show the collection we are working with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
> db.demoCommentCollection.find()
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a48f"),
        "userId" : 1,
        "comment" : "Hi, it's Al again. I really do love comments."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a490"),
        "userId" : 1,
        "comment" : "Hi, I'm Al and I love Object Rocket and I love comments."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a491"),
        "userId" : 3,
        "comment" : "This is Cameron. I enjoyed reading your Object Rocket tutorials."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a492"),
        "userId" : 2,
        "comment" : "I'm Betty. This is my first comment on the site."
}

1. Use the .find() with $regex to find documents containing the search string

Our first step is to search for documents containing ‘Object Rocket’ by using the .find() method which has the following definition:

1
db.<collectionName>.find(<selectionCriteria>, <projection>)

You can use a regular expression in the <selectionCriteria> to look for strings that match a certain pattern. Regex ( Regular Expression ) are a very versatile text pattern matching functionality. They are good to know in programming for any type of simple to complicated string matching. Our simple Regular Expression for an exact match to Object Rocket is /Object Rocket/. The forward slashes indicate beginning and end of regular expression. In this example we search comment field so our MongoDB shell command becomes:

1
db.demoCommentCollection.find({comment:/Object Rocket/})

The exacrt same functionality can also be achieved another using $regex option like:

1
db.demoCommentCollection.find( { 'comment' : { '$regex' : /Object Rocket/}} )

They both result in the same results that retrieves the two records where the phrase Object Rocket appeared in the comment field:

1
2
3
4
5
6
7
8
9
10
11
 >db.demoCommentCollection.find( { 'comment' : { '$regex' : /Object Rocket/}} )
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a490"),
        "userId" : 1,
        "comment" : "Hi, I'm Al and I love Object Rocket and I love comments."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a491"),
        "userId" : 3,
        "comment" : "This is Cameron. I enjoyed reading your Object Rocket tutorials."
}

If you plan on searching through a large number of documents there are better and more performant ways of searching but for a small data set like here or infrequent searches this method should do the job. For solving this type of problem with larger data sets look into topics such as tokenizing, multi-keys, and inverted index.

Conclusion

We showed you two ways search for documents with a given string using the .find() command. This type of search is extremely common and is also a good starting point for jumping into searching for documents using Regular Expressions or Regex. If you’d like to learn more about the options available in these functions, the MongoDB documentations is fairly straightforward and can answer many of your questions. We hope this tutorial was able to answer your question or provide you the snippet of code that you were looking for all along. Thank you for your time and if you have any feedback or questions do not hesitate to reach out to us.

Just the Code

If you’re already comfortable with all the concepts of regex and just need a quick reminder, here’s all the code we used to demonstrate how to search for a string in a field within a MongoDB collection

1
db.demoCommentCollection.find({comment:/Object Rocket/})

Or

1
db.demoCommentCollection.find( { 'comment' : { '$regex' : /Object Rocket/}} )

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.