MongoDB $toLower

In MongoDB, the $toLower aggregation pipeline operator converts a string to lowercase 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 $toLower operator to convert those fields to lowercase strings and return the result.

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

db.pets.aggregate(
  [
    {
      $project:
        { 
          name: { $toLower: "$name" },
          type: { $toLower: "$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 }

In this case, most of the characters were lowercase to begin with, but the first character was uppercase, In all cases, those characters were converted to lowercase and the result was returned.

Converting Non-Strings

You can use $toLower 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 $toLower to convert the weight field to a lowercase string, even though that field only contains numbers.

Example:

db.pets.aggregate(
  [
    {
      $project:
        { 
          name: { $toLower: "$name" },
          type: { $toLower: "$type" },
          weight: { $toLower: "$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 lowercase 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.