Home > Net >  regex in $match mongodb
regex in $match mongodb

Time:07-29

I need to search data in MongoDB. Basically it should search starts with/includes/contains I have collection :

[{
Name: "test",
Code: "LP1234"
},
{
Name: "test1",
Code: "1234"
},
{
Name: "test2",
Code: "lp2277"
}]

Now from Node JS I am searching the data using $match. So if I search I need out put in the following pattern: Search input: 12 Result should be :

[{
Name: "test",
Code: "LP1234"
},
{
Name: "test1",
Code: "1234"
}] 

Search Input(small case): lp Output should be:

[{
Name: "test",
Code: "LP1234"
},
{
{
Name: "test2",
Code: "lp2277"
}]

Please let me know how aggregate query can be formed with $match.

Thanks..

CodePudding user response:

This might work for you:

db.collection.aggregate([
  {
    $addFields: {
      resultObject: {
        $regexMatch: {
          input: "$Code",
          regex: "12",
          options: "i"
        }
      }
    }
  },
  {
    $match: {
      resultObject: true
    }
  }
])

You can try here: https://mongoplayground.net/p/JnyORG8i_Qo

  • Related