This question is in PHP.
I have an array element in my document called tags
.
This member function gives me an array of MongoDB\Model\BSONDocument
:
public function all_tags(int $ascdesc = self::ASC): array {
return $this->mongodb_db->fourberie->aggregate([
['$project' => ['tags' => true]],
['$unwind' => '$tags'],
['$group' => ['_id' => '$tags']],
['$sort' => ['_id' => $ascdesc]]
])->toArray();
}
Now I want only those tags that match a regex. The following function yields no documents for any pattern.
Incorrect code deleted - Jack
Figured it out
/**
* Returns all matching tags as array of doc.
* @return array all unique tags as array of doc
* @param string $pattern pattern to match
* @param bool $case_sensitive should the match be case sensitive, default = true
* @param int $ascdesc ASCending or DESCending sort (optional, default self::ASC)
* @return array of doc for all matching tags
*/
public function all_tags_matching_regex(string $pattern, bool $case_sensitive = true, int $ascdesc = self::ASC): array {
return $this->mongodb_db->fourberie->aggregate([
['$project' => ['tags' => true]],
['$unwind' => '$tags'],
['$match' => ['tags' =>
$case_sensitive ? (['$regex' => $pattern]) : (['$regex' => $pattern, '$options' => 'i'])
]],
['$group' => ['_id' => '$tags']],
['$sort' => ['_id' => $ascdesc]]
])->toArray();
}