通过MongoDB中的匹配字符串查找数据库中的正则表达式

brjng4g3  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(124)

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])$

wbgh16ku

wbgh16ku1#

> 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])$", "") }

您可以使用$regexMatch来检查正则表达式是否与给定的字符串匹配。

> 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 }

您也可以使用$regexFind和$regexFindAll

相关问题