skip to Main Content

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?

2

Answers


  1. Yes, you can use aggregation pipeline that makes specific fields lowercase and than does matching against them, for examples look at
    https://www.mongodb.com/docs/manual/reference/operator/aggregation/toLower/#example
    and https://www.mongodb.com/docs/manual/reference/operator/aggregation/match/#examples

    On large datasets this way of querying would not be efficient, but for one time queries may be useful.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search