2

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?

MongoDB syntax:

db.getCollection('product').aggregate(
   [
      { $match: { 'Store.Title': { $regex: 'apc', $options: 'gi' } } },
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
);

Output from MongoDB:

{
    "result" : [ 
        {
            "_id" : null,
            "count" : 774.0000000000000000
        }
    ],
    "ok" : 1.0000000000000000
}

PHP Filter array:

[
    [
        '$match' => [
            'Store.Title' => ['$regex' => 'apc', '$options' => 'gi']
        ]
    ],[
        '$group' => [
            '_id' => 'null',
            'count' => [ '$sum' => 1 ]
        ]
    ]
]

Output from PHP:

Array
(
    [result] => Array
        (
        )

    [ok] => 1
)

i hope there are simple explaining on this issue thanks for helping guys.

1 Answer 1

1

Use the MongoRegex 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 ]
        ]
    ]
]
Sign up to request clarification or add additional context in comments.

4 Comments

did you try the other $where array? $where = array('Store.Title' => array('$regex' => new MongoRegex("/".$search."/gi")));
Hmm now my jQuery give me "An error occurred trying to load the resource" and block my respons data, its only happen when i use the MongoRegex function but if i run it outsite the jQuery i get the right data back now ( Array ( [result] => Array ( [0] => Array ( [_id] => null [count] => 673 ) ) [ok] => 1 ) )
the last issue, is jquery.ajax has none timeout now before i have set a timeout on it there crash everything, :) thanks a lot for helping
@ParisNakitaKejser No worries, glad that worked out well for you in the end :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.