Run aggregation with $match and $or and $regexMatch from JavaScript?

I am trying to run an aggregation, which at the end should enable a search over all fields.

My idea was to use { “$match”: { “$or”: [ { "$regexMatch: {}} ] } } and just add all field names with the same search string in my Javascript application. But I get an error “MongoServerError: unknown top level operator: $regexMatch”, not sure how to change the aggregation.

let agg = [{
    "$match": {
        "$or": [
            {
                "$regexMatch": {
                    "input": "$field1",
                    "regex": new RegExp(search),
                    "options": "i"
                }
            },
            {
                "$regexMatch": {
                    "input": "$field2",
                    "regex": new RegExp(search),
                    "options": "i"
                }
            },
            ... more fields ...
        ]
    }
}]

Try by enclosing the whole $or within $expr.

Example:

let agg = [{
    "$match": {
        "$expr" : {"$or": [
            {
                "$regexMatch": {
                    "input": "$field1",
                    "regex": new RegExp(search),
                    "options": "i"
                }
            },
            {
                "$regexMatch": {
                    "input": "$field2",
                    "regex": new RegExp(search),
                    "options": "i"
                }
            }
        ] }
    }
}]
2 Likes

Awesome, thank you, that solved it!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.