简体   繁体   中英

mongodb $nin not work in php

Current Code:

$doc = array('ooxx' => array(1,2,3,4,5));

datamodel()->insert($doc);

$doc2 = array('ooxx' => array(6,7,8,9));
datamodel()->insert($doc2);

$macher = array('ooxx'=>array('$exists' => true), 'ooxx' => array('$nin'=>array(6)));
$res = datamodel()->findOne($macher);
print_r($res);

When I replace the $macher with bellow, it does work well, why? is this a bug of mongodb?

$macher = array( 'ooxx' => array('$nin'=>array(6)), 'ooxx'=>array('$exists' => true));

It doesn't work because the keys have the same name and one overwrites the other. So the "keys" need to be unique.

If you have two conditions for the same key you use the $and operator which takes an array of arguments:

$matcher = array(
    '$and' => array( 
        array( 'ooxx' => array( '$nin' => array(6) ) ),
        array( 'ooxx' => array( '$exists' => true ) )
    )
)

Or for the JSON minded:

{
    "$and": [
        { "ooxx": { "$nin": [6] } },
        { "ooxx": { "$exists": true } }
    ]
}

Which is a valid structure where what you are writing is not.

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