Match the regex pattern stored in a field in MongoDB

This question is about the capabilities of MongoDB queries to match the regular expression that is stored in the field.

In the database, I store simple zip regular expression patterns. For example, in the zipcode field:3121, 312*, 313?

Then, if someone enters any string that matches any pattern that needs to be returned. Thus, the user enters one of: "3121", "31222", "3135", and the record must match and be returned. This is a kind of inverse of normal regular expression matching.

I know that I can test each zip code individually in the code, but is it possible to build a mongoDB request to handle correspondence directly?

What would I add to this query?

db.shippingZones.query({}).pretty()

As an example, the document shippingzonewill look like this:

{
  id: 123455678,
  states: ['NSW', 'VIC'],
  zipcodes: ['3121', '312*', '313?']
}

Then, when the user enters "31222", I need a query that will return a sample document, since it matches regular expression 312 *.

+4
source share

Source: https://habr.com/ru/post/1652942/


All Articles