0

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?

Benji
  • 310
  • 3
  • 12

2 Answers2

3

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.

user20042973
  • 4,096
  • 2
  • 3
  • 14
0

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.

  • Thank you. Yeah, I saw that `$toLower` operator in their documentation, and that is precisely want I want to do, and why I included it in the pseudo example I gave, but I don't know how to cast a field as lowercase _in the query itself_, and do the comparison in the first place. I know I need to do something like `str.toLowerCase() === str` but I have no idea how to translate that into a pipeline stage or regular query. `item: { $toLower: "$item" }` returns a lowercase value in a `$project` stage, but doesn't do a lookup on it. – Benji Oct 17 '22 at 12:09
  • When I try to do something like `item: { $toLower: "$item" }` as a query, MongoDB just says `unknown operator: $toLower` which tells me that `$toLower` must be restricted to `$project` operations only. – Benji Oct 17 '22 at 12:12
  • 1
    Please see the next comment using find, it seems valid query example that does this. – Tornike Skhulukhia Oct 17 '22 at 12:14