MongoDB $toUpper

In MongoDB, the $toUpper aggregation pipeline operator converts a string to uppercase and returns the result.

Example

Suppose we have a collection called pets with the following documents:

{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }

We can use the $toUpper operator to convert those fields to uppercase strings and return the result.

Here’s an example of returning the name and type fields in uppercase:

db.pets.aggregate(
  [
    {
      $project:
        { 
          name: { $toUpper: "$name" },
          type: { $toUpper: "$type" },
          weight: "$weight"
        }
    }
  ]
)

Result:

{ "_id" : 1, "name" : "WAG", "type" : "DOG", "weight" : 20 }
{ "_id" : 2, "name" : "BARK", "type" : "DOG", "weight" : 10 }
{ "_id" : 3, "name" : "MEOW", "type" : "CAT", "weight" : 7 }

Converting Non-Strings

You can use $toUpper on values that aren’t necessarily strings. The argument can be any expression as long as it resolves to a string.

For example, we can use $toUpper to convert the weight field to an uppercase string, even though that field only contains numbers.

Example:

db.pets.aggregate(
  [
    {
      $project:
        { 
          name: { $toUpper: "$name" },
          type: { $toUpper: "$type" },
          weight: { $toUpper: "$weight" }
        }
    }
  ]
)

Result:

{ "_id" : 1, "name" : "WAG", "type" : "DOG", "weight" : "20" }
{ "_id" : 2, "name" : "BARK", "type" : "DOG", "weight" : "10" }
{ "_id" : 3, "name" : "MEOW", "type" : "CAT", "weight" : "7" }

We can see that the weight field was converted to a string, because it’s now surrounded by quotes. However, given that this field only contains numbers, there’s no uppercase effect – numbers don’t have uppercase and lowercase, and so we can’t see any difference in respect to case.

If we simply wanted to convert the number to a string, we could have used the $toString operator or even the $convert operator.