MongoDB find string contains

In this MongoDB tutorial, we are going to discuss “MongoDB find string contains”. We will also cover this topic with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • MongoDB find query contains a string
  • MongoDB find string contains a substring
  • MongoDB find string contains in an array
  • MongoDB find string does not contain
  • MongoDB find where the string contains
  • MongoDB find string contains a match
  • MongoDB compass search find string contains

MongoDB find query contains a string

In MongoDB, we can use the $regex operator to find a query that contains a string.

What is $regex in MongoDB?

MongoDB gives the functionality to search a pattern in a string through a query by writing a regular expression. The regular expression capabilities are used for pattern matching strings in queries and for that, we use the $regex operator.

Syntax:

db.collection.find({"yourFieldName":{$regex:"yourValue"}});

Here, we are displaying the documents of those fields containing the value string that we pass in the $regex regular expression operator.

Let’s more understand with the help of an example and find the documents that contain a particular string.

Example:

The following documents were inserted into the empDetails collection:

db.empDetails.insertMany([
	{
		First_Name: "Tom",
		Last_Name: "Noah",
                Country: "United States of America"
	},
	{
		First_Name: "Rachel",
		Last_Name: "Christopher",
                Country: "New Zealand"	
	},
	{
		First_Name: "Fathima",
		Last_Name: "Sheik",
                Country: "United Kingdom"
	}
])

Now, we will use the following query to find the documents that contain a particular string:

db.empDetails.find({ "First_Name": { $regex: "Tom" } })

Here, we define the parameter in the find() method, and the $regex operator is used to find the string where the First_Name is Tom.

MongoDB find query contains a string
MongoDB find query contains a string

Read: MongoDB find multiple conditions

MongoDB find string contains a substring

In this topic, we will learn to find the documents of the collection where the field contains a substring of a string.

Let’s understand with the help of an example and find the substring of a string.

Example:

The following documents were inserted into the courses collection.

db.courses.insertMany([
{"university": "USAL", "name": "Computer Science", "level": "Excellent" },
{"university": "USAL", "name": "Electronics", "level": "Intermediate" },
{"university": "USAL", "name": "Communication", "level": "Excellent" }
])

After that, we apply the subsequent query and find the substring of a string.

db.courses.find({ "name": { $regex: ".*Science.*" } }).pretty()

Here, we define the parameter in the find method as “{ $regex: “.*Science.*” }” that means all the documents whose description field contains in the text the “Science” will return.

MongoDB find string contains a substring
MongoDB find string contains a substring

We have successfully retrieved all the documents having substring of a string and the find() method is used to return the documents in an easy-to-read format.

Read: MongoDB Update Documents

MongoDB find string contains in an array

When we have the documents in an array form in the collection and we only have to find the string contains in an array then we use the $regex (regular expression) operator to find the documents.

Let’s find the documents that contain string in array with the help of an example.

Example:

These documents were inserted into the book collection.

db.book.insertMany([
{
        "_id" : 1,
        "item" : "Data Modeling for MongoDB",
        "stock" : 4,
        "info" : {
                "publisher" : "2222",
                "pages" : 480
        },
        "tags" : [
                "software"
        ],
        "ratings" : [
                {
                        "by" : "Kyle",
                        "rating" : 4
                },
                {
                        "by" : "Honey",
                        "rating" : 3
                }
        ],
        "reorder" : false
},
{
        "_id" : 2,
        "item" : "MongoDB: The Definitive Guide",
        "stock" : 15,
        "info" : {
                "publisher" : "5555",
                "pages" : 150
        },
        "tags" : [ ],
        "ratings" : [
                {
                        "by" : "Bob",
                        "rating" : 5
                }
        ],
        "reorder" : false
}
])

Now, we will apply the below query to find the documents in which the string contains in an array:

db.book.find({ "ratings.by": { $regex: "Kyle" } }).pretty()

Here, we find the documents where the array string is Kyle by using the regular expression $regex operator. The “ratings. by” where . is used to access the sub-field.

MongoDB find string contains in array
MongoDB find string contains in array

Read: How to drop a database in MongoDB

MongoDB find string does not contain

In this topic, we will find strings does not contain in the documents. For that, we will use the regular expression $regex operator for string matching and the $not operator for not containing in the documents.

Let’s understand with the help of an example and find documents where string does not contain.

Example:

In the example, we use the same collection book as we used in the above topic. For reference, you can check the above topic:

MongoDB find string does not contain
MongoDB find string does not contain

We will apply the below query to find documents where the string does not contain:

db.book.find({ "item": { $not: {$regex: /Data/ }}}).pretty()

Here, we have used the $not operator to retrieve those documents that do not match the given operator expression and in the $regex (regular expression) operator we assign the /Data/ for pattern matching string.

This query will check in the whole collection and retrieve only those documents where the Data string is not in the item field.

MongoDB find string does not contain in the document
MongoDB find string does not contain in the document

Also, check: Export MongoDB to CSV

MongoDB find where the string contains

When we want to find out the documents with conditions “where the string contains” then we will use the regular expression $regex operator and in which define the value string that we want to find.

Now, we will understand with the help of an example and find documents where the string contains.

Example:

The following documents were inserted into the details collection.

db.details.insertMany([
{
        "First_Name" : "James",
        "Last_Name" : "Shaw",
        "Age" : "29",
        "e_mail" : "James_Shaw.321@gmail.com",
        "phone" : "9000012345"
},
{
        "First_Name" : "Rachel",
        "Last_Name" : "John",
        "Age" : "28",
        "e_mail" : "Rachel_John.123@gmail.com",
        "phone" : "9000054321"
},
{
        "First_Name" : "George",
        "Last_Name" : "Wood",
        "Age" : "23",
        "e_mail" : "George_Wood.123@gmail.com",
        "phone" : "9000054321"
},
{
        "First_Name" : "Rachel",
        "Last_Name" : "Shaw",
        "Age" : "29",
        "e_mail" : "Rachel_Shaw101@gmail.com",
        "phone" : "9900012345"
}
])

Now, we will apply the below query to find where the string contains:

db.details.find({ "First_Name": { $regex: "^Rachel$" } }).pretty()

Here, we are using ^ and $ characters. The ^ is used to string start with a certain character and $ is used to ensure that the string ends with a certain character. After executing the code it will only retrieve those documents where the string is “Rachel”.

MongoDB find where the string contains
MongoDB find where the string contains

We successfully return the documents where the string contains is Rachel. The find() method is used to retrieve the documents in an easy-to-read format.

Read: MongoDB join two collections

MongoDB find string contains a match

In this topic, we will understand to find the string that contains a match. When we use the $regex operator then we can also provide additional options by using the $options keyword.

The use of the $options operator is to match the string whether it was case sensitive or insensitive. For example, suppose we want to find all the documents which had “Co” in their subject field, irrespective of whether it was case sensitive or insensitive.

Example:

The subsequent documents were inserted into the store collection.

db.store.insertMany([
{"_id": 1, "subject": "coffee", "author": "xyz", "views": 50 },
{"_id": 2, "subject": "Coffee Shopping", "author": "efg", "views": 5 },
{"_id": 3, "subject": "Baking a cake", "author": "abc", "views": 90 },
{"_id": 4, "subject": "baking", "author": "xyz", "views": 100 },
{"_id": 5, "subject": "Café Con Leche", "author": "abc", "views": 20 }
])

After that, we will apply the below query to find a string contains a match:

db.store.find({ "subject": { $regex: "Co", $options: "i" } })

Here, The $options with the “i” parameter specify that we want to carry out the search no matter if we find the letters ‘Co’ in lower or upper case.

MongoDB find string contains a match
MongoDB find string contains a match

Read: Import CSV into MongoDB

MongoDB compass search find string contains

In MongoDB compass, we can search and find all the documents where the field contains string by using the $regex operator.

Let’s understand with the help of an example and find documents where the string contains.

Example:

You have to follow the below steps without any fall then you will easily find out the documents that contain string:

  • Open MongoDB Compass and connect to the server.
  • Select the database and collection or either create a new database and collection and insert the documents.
  • Here, we are using an existing database and collection, mydatabase and store respectively.
MongoDB compass search find string contains
MongoDB compass search find string contains
  • Click on OPTIONS drop-down button on the left side of the FIND button.
  • And it provides various option that can perform FILTERPROJECTSORT, and COLLATION.
  • Now, we define following two queries and find string contains from the documents as per the condition.
{"subject": {$regex: "Co", $options: "a"}} # Define in FILTER section

{ "author": -1}      # Define in SORT section

Here, we define a query where the document contains the string “Co” and the $options with a parameter specify that we want to carry out the search if we find the letters ‘Co’ only in lower case. The sort section query is used to sort the data in descending order -1 as per the author field.

  • After applying the query click on the FIND button and this will find all string contains documents.
MongoDB compass search find string contains document
MongoDB compass search find string contains document

We have successfully found all the documents that contain string using MongoDB Compass.

You may also like to read the following MongoDB tutorials.

In this tutorial, you have learned about “MongoDB find string contains” with different operations and examples. And we have also covered the following list of topics:

  • MongoDB find query contains a string
  • MongoDB find string contains a substring
  • MongoDB find string contains in an array
  • MongoDB find string does not contain
  • MongoDB find where the string contains
  • MongoDB find string contains a match
  • MongoDB compass search find string contains