And operator of two sets in MongoDB for Laravel using Jenssegers -
i'm trying mimick mongodb query in laravel using jenssegers eloquent model.
the query one:
db.getcollection('users').find({ $and : [ {$or : [ { "user.gender" : "male"}, {"user.location" : "nyc"} ]}, {$and : [ {"user.name" : "user name"}, {"user.id" : "10143224362247922"} ]} ] })
it , of 2 sets, being first set being or of values while second set being , of values.
i'm using following query:
$query = array( '$and' => array( '$or' => array( "user.gender" => "male", "user.location" => "nyc", ), '$and' => array( "user.name" => "user name", "user.id" => "10143224362247922", ), ) ); $cursor = user::raw()->find($query, array( "_id" => false, ));
but error: can't canonicalize query: badvalue , needs array
what i'm doing wrong?
your php syntax representing true arrays wrong in couple of places here, have tied in unnecessary knots because initial understanding of mongodb query syntax missed points in beginning.
though initial query work both $and
operations use not necessary because arguments in mongodb query considered "implicit and" operation unless stated otherwise.
it can therefore more efficiently written as:
db.getcollection('users').find({ "$or" : [ { "user.gender" : "male"}, { "user.location" : "nyc"} ], "user.name" : "user name", "user.id" : "10143224362247922" })
or in php syntax so:
$query = array( '$or' => array( array( "user.gender" => "male" ), array( "user.location" => "nyc" ) ), array( "user.name" => "user name" ), array( "user.id" => "10143224362247922" ) );
however there still mind 1 problem here. if intent match these properties in single element of array query not work.
the way matching arrays works mongodb conditions can match any array element of array. conditions may present in array items, not in one element.
for case use $elemmatch
applies it's own set of query conditions each array element test. when conditions met particular element element ( , therefore document ) considered match:
db.getcollection('users').find({ "user": { "$elemmatch": { "$or": [ { "gender" : "male"}, { "location" : "nyc" } ], "name" : "user name", "id" : "10143224362247922" } } })
and php:
$query = array( 'user' => array( '$elemmatch' => array( '$or' => array( array( "gender" => "male" ), array( "location" => "nyc" ) ), array( "name" => "user name" ), array( "id" => "10143224362247922" ) ) ) );
so "dot notation" using fine "single" conditions on array elements. "multiple" conditions use $elemmatch
instead.
also on related note, if having trouble converting typical json syntax examples find work shell can test php structures json_encode
. @ least shows json serialization can compare. decent tool logging, imho best initial way debug in application.
Comments
Post a Comment