1

I have a database in mongoDb, one of the fields in one of my collections is a Regular expression.

I need to match some string, and find which regexp fits to that string. However, for performance issues, I don´t want get every item in the collection and make a try and error for every regular expression in there.

Is there any way I can make a query to my collection sending the String I want to match with a specific collection's regular expression?

An example is I send in a query 1900-01-01 and it must give me the object that has the regexp ^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$

Noel
  • 10,152
  • 30
  • 45
  • 67
Ricardo Mogg
  • 589
  • 6
  • 18

1 Answers1

0
> db.col.find();
< { _id: ObjectId("6392dcac3bb5b657347cbd70"),
    regexField: BSONRegExp("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", "") }

You can make use of $regexMatch to check if the regex matches a given string.

> db.col.aggregate([
    {
      $addFields: {
        "doesItMatch": {
          $regexMatch: {
            input: "1900-01-01", regex: "$regexField"
          }
        }
      }
    }
  ]);
< { _id: ObjectId("6392dcac3bb5b657347cbd70"),
    regexField: BSONRegExp("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", ""),
    doesItMatch: true }

You can also use $regexFind and $regexFindAll

Noel
  • 10,152
  • 30
  • 45
  • 67