Learning MongoDB

0% completed

Previous
Next
String Operators

String operators in MongoDB are used to perform operations on string values within documents. These operators enable you to search, manipulate, and transform string data, providing powerful tools for text-based queries and updates.

Understanding these operators is essential for effectively managing and querying string data in MongoDB.

String Operators

OperatorDescription
$regexMatches strings using regular expressions.
$textPerforms text search on the content of the fields indexed with a text index.
$indexOfBytesReturns the position of a substring within a string, measured in bytes.
$indexOfCPReturns the position of a substring within a string, measured in code points.
$concatConcatenates multiple strings into a single string.
$substrReturns a substring from a string, starting at a specified index and including the specified number of characters.
$toLowerConverts a string to lowercase.
$toUpperConverts a string to uppercase.
$trimRemoves whitespace or specified characters from the beginning and end of a string.
$ltrimRemoves whitespace or specified characters from the beginning of a string.
$rtrimRemoves whitespace or specified characters from the end of a string.
$splitSplits a string into an array of substrings based on a delimiter.
$strLenBytesReturns the number of bytes in a string.
$strLenCPReturns the number of code points in a string.
$strcasecmpPerforms a case-insensitive comparison of two strings.

Syntax for Using String Operators

The general syntax for using string operators in MongoDB is:

db.collection.aggregate([ { $project: { <field>: { <operator>: [ <expression1>, <expression2>, ... ] } } } ])
  • field: The field to project.
  • operator: The string operator to apply.
  • expression1, expression2, ...: The string expressions to operate on.

However, you can use different string operators with different methods. In this lesson, we have used the find(), createIndex(), etc. methods in various examples.

Example Setup

First, let's insert some documents into the users collection to work with:

db.users.insertMany([ { name: "Alice", description: "Alice loves reading and traveling." }, { name: "Bob", description: "Bob enjoys cycling and hiking." }, { name: "Charlie", description: "Charlie likes gaming and reading." }, { name: "David", description: "David prefers swimming and biking." }, { name: "Eve", description: "Eve is fond of running and painting." } ])

$regex Operator

The $regex operator matches strings using regular expressions. This is useful for pattern matching and complex string searches.

Examples

  1. Find Users Whose Description Contains "reading"

    db.users.find({ description: { $regex: /reading/ } })

    This command finds documents where the description field contains the word "reading". For example, it will match the documents for "Alice" and "Charlie" because their descriptions include "reading".

  2. Find Users Whose Description Starts with "Alice"

    db.users.find({ description: { $regex: /^Alice/ } })

    This command finds documents where the description field starts with the word "Alice". For example, it will match the document for "Alice".

$text Operator

The $text operator performs a text search on the content of the fields indexed with a text index. This is useful for full-text search capabilities.

Examples

  1. Create a Text Index and Search for "reading"

    db.users.createIndex({ description: "text" }) db.users.find({ $text: { $search: "reading" } })

    This command first creates a text index on the description field. Then, it performs a text search for the word "reading". For example, it will match the documents for "Alice" and "Charlie" because their descriptions include "reading".

  2. Search for Multiple Terms "reading" and "traveling"

    db.users.find({ $text: { $search: "reading traveling" } })

    This command performs a text search for the words "reading" and "traveling". For example, it will match the document for "Alice" because her description includes both words.

$concat Operator

The $concat operator concatenates multiple strings into a single string.

Examples

  1. Concatenate Name and Description

    db.users.aggregate([ { $project: { fullDescription: { $concat: ["$name", " - ", "$description"] } } } ])

    This command concatenates the name and description fields with a hyphen in between to create a fullDescription field. For example, if "Alice" has the description "Alice loves reading and traveling.", the fullDescription will be "Alice - Alice loves reading and traveling.".

$substr Operator

The $substr operator returns a substring from a string, starting at a specified index and including the specified number of characters.

Examples

  1. Extract Substring from Description

    db.users.aggregate([ { $project: { shortDescription: { $substr: ["$description", 0, 10] } } } ])

    This command extracts the first 10 characters from the description field for each document. For example, if "Alice" has the description "Alice loves reading and traveling.", the shortDescription will be "Alice love".

$toLower Operator

The $toLower operator converts a string to lowercase.

Examples

  1. Convert Description to Lowercase

    db.users.aggregate([ { $project: { lowerDescription: { $toLower: "$description" } } } ])

    This command converts the description field to lowercase for each document. For example, if "Alice" has the description "Alice loves reading and traveling.", the lowerDescription will be "alice loves reading and traveling.".

$toUpper Operator

The $toUpper operator converts a string to uppercase.

Examples

  1. Convert Description to Uppercase

    db.users.aggregate([ { $project: { upperDescription: { $toUpper: "$description" } } } ])

    This command converts the description field to uppercase for each document. For example, if "Alice" has the description "Alice loves reading and traveling.", the upperDescription will be "ALICE LOVES READING AND TRAVELING.".

$trim Operator

The $trim operator removes whitespace or specified characters from the beginning and end of a string.

Examples

  1. Trim Whitespace from Description

    db.users.aggregate([ { $project: { trimmedDescription: { $trim: { input: "$description" } } } } ])

    This command removes any leading and trailing whitespace from the description field for each document. For example, if "Alice" has the description " Alice loves reading and traveling. ", the trimmedDescription will be "Alice loves reading and traveling.".

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next