Benji
Benji

Reputation: 380

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?

Upvotes: 0

Views: 1679

Answers (2)

user20042973
user20042973

Reputation: 5065

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.

Upvotes: 3

Tornike Skhulukhia
Tornike Skhulukhia

Reputation: 421

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.

Upvotes: 0

Related Questions