'MongoDB - Return all regex matches from an Array
I have a mongoDB document that contains a list of email address. I'd like to use a regEx expression to return an array of matching email address in the single document. I don't need to find all matches in the Collection. I'm assuming I need to use aggregation but I can't get it to work correctly. Any advice?
{
"_id": {
"$oid": "621fbc842ff7d84973d537e7"
},
"name": "Test",
"emailAddresses": ["[email protected]", "[email protected]", "[email protected]", "[email protected]"],
"_class": "com.email.models.Group"
}
Search for "ema", would return:
{
"emailAddresses": ["[email protected]", "[email protected]", "[email protected]" ]
}
Solution 1:[1]
Something like this:
db.collection.aggregate([
{
$addFields: {
emailAddresses: {
$filter: {
input: "$emailAddresses",
cond: {
"$regexMatch": {
input: "$$this",
regex: "ema"
}
}
}
}
}
}
])
Explained:
Define addFields aggregation stage with $filter to replace the original emailAddresses array , in the input for the filter provide the emailAddresses array and condition for the filter add regex expression by which the array elements will be filtered.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
