Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A variable in regular expressions (regex) for MongoDB's aggregate function can be utilized in several ways:

  1. As a string variable to hold the regex pattern: You can store the regex pattern in a string variable and use it in the aggregate pipeline as a parameter of the $regex operator.

Example:

const regexPattern = "foo|bar";
db.collection.aggregate([
   {
      $match: {
         field: {
            $regex: regexPattern
         }
      }
   }
]);
  1. As a parameter to a regex method: You can use variables to pass parameters to regex methods like $regexFind or $regexMatch in the aggregate pipeline.

Example:

const regexPattern = /foo(\d)/;
db.collection.aggregate([
   {
      $project: {
         result: {
            $regexFind: {
               input: "$field",
               regex: regexPattern,
               options: "i"
            }
         }
      }
   }
]);
  1. As a dynamically generated regex pattern: You can create a regex pattern dynamically using variables and string concatenation based on your requirements.

Example:

const searchKeyword = "foo";
const regexPattern = new RegExp(".*" + searchKeyword + ".*", "i");
db.collection.aggregate([
   {
      $match: {
         field: {
            $regex: regexPattern
         }
      }
   }
]);