Search code examples
mongodbif-statementconditional-statementsmatchaggregation

Is it possible to match with what comes after a character in MongoDB?


I'm trying to make a match aggregation query to my mongoDB. If th string I'm trying to match has a backslash it should only match on whatever is behind the backslash.

For example, if the string in the database is Mike\Peter i only want to match on Peter.

$match {
  'name': 'Peter'
}

Obviously this query will not match because Mike\Peter does not match Peter, so are there any way to check if the string contains \ and if so, then only match with what comes after?


Solution

  • You need to use $regex and escape the special character.

    Sample

    [
      {
        "key": "Mike\\Peter"
      },
      {
        "key": "Peter"
      }
    ]
    
    db.collection.find({
      key: {
        "$regex": "\\\\Peter"
      }
    })