Search code examples
phpmongodbmongodb-queryphp-mongodb

Fetch documents with condition on "array of objects" field in MongoDB with PHP


I saw other similar questions to query array fields but most of them were for pure Mongo and I couldn't translate the solutions to PHP's driver 'find()'.

I also found a similar question here but I couldn't use it to solve my problem.

The PHP driver's documentation wasn't helpful as well, there's a single example for find() but the fields are not arrays like mine.

The field causing me trouble is "Sentenca", it's an array which contains "Situacao" and "Prob". Like the following:

"Sentenca": [{
        "Situacao": "nc",
        "Prob": 0.96
        }]

enter image description here

"Sentenca" always contains only one index [0] with these two fields.

I need to query all documents where "Situacao" is NOT "nc". All I know is that I should use the operar $nin but I have no idea how to do that using find().

The furthest I got is this (and this query isn't doing what I need):

$result = $collection->find( [ "Sentenca"=>["Situacao"=>['$nin'=>["nc"]]]] );

EDIT: I managed to make a query applying the $nin conditions for "Situacao" but for some reason this query returns nothing. If I try to echo the entries I get the error:

Uncaught MongoDB\Driver\Exception\LogicException: Cursors cannot yield multiple iterators

Solution

  • Someone on MongoDB forum solved the issue. You can use '.' to access an array element, then use $nin => 'nc'.

    $result = $collection->find([
    
        "Sentenca.0.Situacao" => [
            '$nin' => ["nc"]
        ]
        
    ]);