regex as $filter in projection
As per @zangw's answer,
this ISSUE-SERVER-8892, According this issue Use $regex as the expression in a $cond, the $regex could NOT be used with cond for current mongo version.
MongoDB v4.1.11 has launched new features in ISSUE-SERVER-11947, This features adds three new expressions $regexFind
, $regexFindAll
and $regexMatch
to the aggregation language.
In your example, You can use $regexMatch expression,
Model.aggregate([
{
$project: {
tags: {
$filter: {
input: "$tags",
cond: {
$regexMatch: {
input: "$$this",
regex: query
}
}
}
}
}
}
])
Playground
According this issue Use $regex as the expression in a $cond
, the $regex
could NOT be used with cond
for current mongo version.
Maybe you can try this one, filter the area3
through $match
, then get all matched tags through $group
, then remove the _id
through $project
.
caseNote.aggregate([{$unwind: '$tags'},
{$match: {tags: /area3/}},
{$group: {_id: null, tags: {$push: '$tags'}}},
{$project: {tags: 1, _id: 0}}])
.exec(function(err, tags) {
if (err)
console.log(err);
else
console.log(tags);
});
Results:
{ "tags" : [ "C area3", "b_area3" ] }