• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB Check if a Field Contains a String

You can easily check if the field contains a string or not in MongoDB by using $regex and $text operators. MongoDB also offers more methods to find a field containing a string in the specified document.

Advertisements

To test whether a field includes a string on the documents, let’s consider a sample collection called student with the following documents. 


# Create collection
db.student.insertMany([
    { 
        _id:1,
        name: "Alice Mark",
        email: "[email protected]",
        age: 15,
        grade: "A",
        remarks: "Excellent result, nice going"
    },
    { 
       _id:2,
        name: "Vicky Jeo",
        age: 14,
        email: "[email protected]",
        grade: "C",
        remarks: "Need-Improvement, need more efforts"
    },
    { 
        _id:3,
        name: "Jermey Gilbert",
        email: "[email protected]",
        age: 17,
        grade: "B",
        remarks: "Good result, keep it up"
    },
    { 
       _id:4,
        name: "Alaric steve",
        email: "[email protected]",
        age: 19,
        grade: "A",
        remarks: "Excellent, nice going"
    }
])

1. Using the $regex Operator:

The $regex operator is used to check if a document field contains a specific string in MongoDB. The $regex operator allows for regular expression matching within the specified field.  

Regular expressions can be used to search for defined patterns or variations of the desired string, making it a versatile method for string searching. Here is the query which returns all documents in the student collection where the field email contains the specified regular expression pattern gmail.com. The regular expression pattern is specified to the $regex operator. 


# Usage of $regex operator
db.student.find({"email":{$regex:"gmail.com"}});

Thus, we obtain the result as displayed below.

field contains a string in MongoDB

2. Using the $text Operator:

Alternatively, using the $text operator also determines whether a field includes a string in MongoDB. Here, the operator performs a text search on the specified field, allowing for efficient full-text search capabilities. The $text operator also supports options such as case sensitivity, stemming, and language-specific search capabilities.

Note that the $text method requires that a text index be created on the collection, otherwise, it will throw a MongoDB error. Run the following:


# Usage of text operator
db.student.createIndex({remarks:"text"})

Consider the following query which returns all documents in the student collection where any field contains the string nice. Further, the $caseSensitive operator is given a true value to check the case insensitivity of the string nice.


# Usage of $caseSensitive operator
db.student.find({ $text: { $search: "nice", $caseSensitive: true} })

The output is displayed here.

3. Using the $in Operator:

In addition to these methods, MongoDB also provides the $in operator which can be used to search for an exact match or partial match within a field. The $in operator accepts an array of elements and returns documents where any of the elements in the array are present in the specified field.

Here is the query which finds all documents where the name field contains either Alice Mark or Alaric Steve by using the $in operator.


# Usage of $in operator
db.student.find({ name: { $in: ["Alice Mark", "Alaric Steve"] } })

The above query gives the following output:

field contains a string in MongoDB

4. Using the $type Operatorto find string field in MongoDB:

However, we have a $type method in MongoDB that is used to select documents based on the data type of a field. It can be used to check if a field contains a string by specifying the data type as string in the query. Here is an example query where the $type operator checks whether the name field contains the string.


# Usage of $type operator
db.student.find({ "name": { "$type": "string" } })

Here’s the output of all the documents whose name field is a string. Moreover, we can use the $regex operator with the $type operator to check if the specified field has the pattern string.

field contains a string in MongoDB

More details about the $type operator can be found here.

5. Using the $where Operator to find string field in MongoDB:

Another way to search for a string within a field is to use the $where operator. It permits filtering documents using JavaScript expressions according to the given criteria. While this method may provide more flexibility in terms of the criteria that can be specified.

It may also be less efficient than other methods due to the use of JavaScript evaluation. Consider the below query which returns all documents in the collection where the field contains the string Excellent.


# Usage of $where operator
db.student.find({ $where: function() { return this.remarks.includes("string"); } })

The output yielded after executing the above command:

field contains a string in MongoDB

6. Conclusion:

In conclusion, MongoDB offers multiple methods to check if a field contains a specific string, we have looked at each of these methods with examples, advantages, and use cases. By utilizing these methods, users can efficiently and effectively search for documents based on specific string values within their database.