87276

I'm trying to use this MongoDB command and filter, its dosen work when i translate it to PHP, hope there are one there can help me to explain why its not working?
<strong>MongoDB syntax:</strong>
db.getCollection('product').aggregate(
[
{ $match: { 'Store.Title': { $regex: 'apc', $options: 'gi' } } },
{ $group: { _id: null, count: { $sum: 1 } } }
]
);
<strong>Output from MongoDB:</strong>
{
"result" : [
{
"_id" : null,
"count" : 774.0000000000000000
}
],
"ok" : 1.0000000000000000
}
<strong>PHP Filter array:</strong>
[
[
'$match' => [
'Store.Title' => ['$regex' => 'apc', '$options' => 'gi']
]
],[
'$group' => [
'_id' => 'null',
'count' => [ '$sum' => 1 ]
]
]
]
<strong>Output from PHP:</strong>
Array
(
[result] => Array
(
)
[ok] => 1
)
i hope there are simple explaining on this issue thanks for helping guys.
Answer1:
Use the <strong>MongoRegex
</strong> object:
$search = "apc";
$where = array('Store.Title' => array('$regex' => new MongoRegex("/^$search/gi")));
// $where = array('Store.Title' => array('$regex' => new MongoRegex("/".$search."/gi")));
[
[ '$match' => $where ],
[
'$group' => [
'_id' => 'null',
'count' => [ '$sum' => 1 ]
]
]
]