Home > Net >  MongoDB query that looks for documents with lowercase values
MongoDB query that looks for documents with lowercase values

Time:10-17

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?

CodePudding user response:

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.

CodePudding user response:

Are you asking to search for string with lowercase or you want to return its value in lowercase

CodePudding user response:

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.

  • Related