PHP MongoDB\Collection->find(): Fetch documents with condition on an Array element

I saw similar questions for this, but I don’t know how to use PHP’s find() to solve it.

I have an Array of objects that always has two field and one index [0].
Like this:

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

image

I want to fetch all documents where ‘Situacao’ $nin ‘nc’. I’m new to MongoDB so I don’t know how to use PHP’s find() for this, the only example from the documentation uses simple fields

EDIT: I managed to create this query, trying to fetch documents where ‘Situacao’ not in “nc”
$result = $collection->find( ["Sentenca"=>["Situacao"=>['$nin'=>["nc"]]]] );

But this query returns nothing and if I try to print it I get the error:

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

If you want to fetch documents where “Situacao” not in “nc”, you can use this PHP code:

$result = $collection->find([

    "Sentenca.0.Situacao" => [
        '$nin' => ["nc"]
    ]
    
]);

print_r($result->toArray());
1 Like

Oh, so I use ‘.’ to access array elements, thank you for you help.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.