Search code examples
phpmongodbphp-mongodb

query with a field in several conditions in mongodb


I need to make a query like this:

db.subscribers.find({LISTID: 59, {$or: [{LANG: {$in: ['English', 'Spanish']} }, 
                                        {LANG: {$nin: ['Russian']} }]}  });

It's supposed to get all subscribers from listid 59, who know English or Spanish or(and) doesn't know Russian. Instead of language there could be any field that can have multiple values. It looks like this query works in mongodb console. In this case one field can be in several conditions. I there is the same field wouldn't be in several conditions, maybe it could be something like:

$collection->find(array('LISTID' => $listId, 
                        array('$or' = array(LANG => array('$in' =>  array('English','Spanish')),

/*some other condition united with OR*/
                                                                        )));

How to make this query in php?


Solution

  • It's supposed to get all subscribers from listid 59, who know English or Spanish and doesn't know Chinese.

    If that's the objective of your query (I assume you mean "Russian" instead of "Chinese"), I don't see how your original console query works:

    db.subscribers.find({
        LISTID: 59,
        { $or: [
            { LANG: { $in: ["English", "Spanish"] } },
            { LANG: { $nin: ["Russian"] } }
        ] }
    });
    

    $or needn't be nested in its own object according to the documentation. Also, if you're looking for documents with a given LISTID that know two languages but not another, $and seems more appropriate:

    db.subscribers.find({
        LISTID: 59,
        $and: [
            { LANG: { $in: ["English", "Spanish"] } },
            { LANG: { $ne: "Russian" } }
        ]
    });
    

    This would translate to PHP as:

    $collection->find(array(
        'LISTID' => $listId,
        '$and' => array(
            array('LANG' => array('$in' => array('English', 'Spanish'))),
            array('LANG' => array('$ne' => 'Russian')),
        ),
    ));