KristCont KristCont - 7 months ago 18
PHP Question

Convert Mongo Shell $or to PHP Syntax

I am a newbie so please have patience. I want to convert this robomongo query to mongolid query:

db.getCollection('products').find({'images':{$size:0},
$or:[
{'inventory.a':{'$gt':0}},
{'inventory.b':{'$gt':0}}
]
})


Below is what I have right now which throws an error
Can't canonicalize query: BadValue $or needs an array
:

$products = Product::where([
'images' => [ '$size' => 0 ],
'$or' => [
'inventory.a' => ['$gt' => 0],
'inventory.b' => ['$gt' => 0]
]
]);

Answer

You are missing brackets around the inner keys of $or:

$products = Product::where([
    'images' => [ '$size' => 0 ], 
     '$or' => [ 
            [ 'inventory.a' => ['$gt' => 0] ],
            [ 'inventory.b' => ['$gt' => 0] ]
     ]
]);

The MongoDB notation is a "list" of "objects", rather than as a "single object with multiple keys" as you notated.

When comparing to JSON, you should dump the JSON encoding to check:

echo json_encode($query, JSON_PRETTY_PRINT);

That way you can spot the differences in how you represented the structure.

Comments