Search code examples
mongodbmongodb-compass

MongoDB query that looks for documents with lowercase values


Is it possible to make a MongoDB query that searches a field for completely lowercase string values?

Something like this pseudo query perhaps?

{ address: { $eq: { $toLower: "$address" } } }

...that would return docs with data like: { "address": "123 main st" }, but won't return docs like { "address": "123 Main St" }, or is such a query not possible with MongoDB?


Solution

  • Based on the clarification, yes what you want is possible and you were pretty close with the original syntax. Try something like the following:

    db.collection.find({
      $expr: {
        $eq: [
          {
            $toLower: "$address"
          },
          "$address"
        ]
      }
    })
    

    Playground link is here.

    There may be some extra considerations depending on language, collation, etc. But this should serve as a good starting point.