New Regex() inside an aggregation pipeline

is there any way to use new RegExp() inside an aggregation pipeline for example

formulationRegex: new RegExp({$arrayElemAt:[{$split:[“$formulation”," "]},0]},“i”)

when I do this I get a result showing this:

formulationRegex: /[object Object]/i


No, you can’t use new RegExp() in MongoDB’s aggregation pipeline. Here’s how to achieve a similar result:

  $project: {
    formulationRegex: { $toString: { $arrayElemAt: [{ $split: ["$formulation", " "] }, 0] } }

This efficiently extracts the first word from the formulation field and converts it to a string for potential regex matching later.

Add ^ (caret) at the beginning of the projection to match the word at the start.