0
0
MongoDBquery~5 mins

String expressions ($concat, $toUpper, $toLower) in MongoDB

Choose your learning style9 modes available
Introduction

String expressions help you join words or change their case in your data. This makes text easier to read or compare.

You want to join a first name and last name into a full name.
You need to make all letters uppercase for consistency.
You want to convert text to lowercase before searching.
You want to create a greeting message by joining words.
You want to standardize email addresses by making them lowercase.
Syntax
MongoDB
1. {$concat: [string1, string2, ...]}
2. {$toUpper: string}
3. {$toLower: string}

$concat joins multiple strings into one.

$toUpper changes all letters to uppercase.

$toLower changes all letters to lowercase.

Examples
Joins "Hello", a space, and "World" to make "Hello World".
MongoDB
{ $concat: ["Hello", " ", "World"] }
Changes "hello" to "HELLO".
MongoDB
{ $toUpper: "hello" }
Changes "WORLD" to "world".
MongoDB
{ $toLower: "WORLD" }
Sample Program

This query creates three new fields for each user: fullName joins first and last names, shoutName makes the first name uppercase, and whisperName makes the last name lowercase.

MongoDB
db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      shoutName: { $toUpper: "$firstName" },
      whisperName: { $toLower: "$lastName" }
    }
  }
])
OutputSuccess
Important Notes

Make sure the fields you use exist and contain strings to avoid errors.

$concat can join more than two strings, including spaces or symbols.

$toUpper and $toLower only affect letters; numbers and symbols stay the same.

Summary

$concat joins strings together.

$toUpper changes text to uppercase.

$toLower changes text to lowercase.