简体   繁体   中英

Find MongoDB data with PHP

Mongodb search with PHP code:

$cond=array();
$cond=array_merge($cond,array("clicks" => array('$gt' =>6)));     

if (isset($lang)){
   $cond=array_merge($cond,array("$or" => array(array("lang" =>'de'),array("lang" =>'fr'))));
}

if (isset($country)){    
   $cond=array_merge($cond,array("$or" => array(array("country" =>'us'),array("country" =>'uk'))));
}

Problem: On the last line, the second $or of country is replacing the first $or of lang. Would be great if anyone can suggest how can we avoid this overriding issue?

Actually I'm new to MongoDB, I want to create a find query in MongoDB. I have to build the query on the basis of some condition flags (eg if '$country=true' only then embed country filter) for each column. Similar to SQL The output I need is:

"Where clicks > 6 and (lang = 'de' or lang = 'fr') and (country = 'us' or country = 'uk')"

This is how your resulting array should look like:

$cond = [
    '$and' => [
        ['clicks' => [ '$gt' => 6 ]],
        ['$or' => [
            [ 'lang' => 'de' ],
            [ 'lang' => 'fr' ]
        ]],
        ['$or' => [
            [ 'country' => 'us' ],
            [ 'lang' => 'uk' ]
        ]]
    ]
];

Now, to achieve this by using the modular approach you have specified, you could do something like this:

$cond = [
    '$and' => [
        ['clicks' => [ '$gt' => 6 ]]
    ]
];

if (isset($lang)) {
    $cond['$and'][] = ['$or' => [['lang' =>'de'], ['lang' =>'fr']]];
}
if (isset($country)) {
    $cond['$and'][] = ['$or' => [['country' =>'us'], ['country' =>'uk']]];
}

Hopefully this will demonstrate the way to assemble nested or/and query in PHP, so you can adjust it further as your design will demand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM