0

Writing a MongoDB regex query in Spring with a field that can be null.

I want to query documents by name and phone:

Query(value = "{ {'name' : {$regex:?0,$options:'i'}},
                          {'phone' : {$regex:?1,$options:'i'}} }")
Document findByFullNameOrPhone(String fullName, String phone);

The value I'm passing through the query for phone is ".*" in an attempt to match everything.

It works but the problem is phone is a field that can be null. If the document has no phone value it's not included in the query result. Is it possible to use this query to find all documents in the database, even if the document does not have a value for phone?

3
  • Why to use Regex? Use something like this: db.mycollection.find({"IMAGE URL":{$ne:null}}); More here Commented Feb 4, 2023 at 10:08
  • Because it's not only used to find all, I also want to be able to find documents where name and/or phone match the value I pass through the regex. Commented Feb 4, 2023 at 10:30
  • Pretty sure "$regex" will only try to match strings. Is replacing null with "" (empty string) in the docs an option? Commented Feb 5, 2023 at 8:14

1 Answer 1

0

Just add null check.

Query(value = "{
  'name': {'$regex': ?0,'options': 'i'},
  $or: [
    {'phone': null},
    {'phone': {'$regex': ?1,'options': 'i'}}
  ]
}")
Document findByFullNameOrPhone(String fullName, String phone);

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.