Shaggie
Shaggie

Reputation: 1829

Find query with and operator in PHP

Hi i am working on backend of web application & want to find the documents from mongodb database that contain key active_status with value set to both 1 & 2. With mongodb PHP i am confused of how to find with both parameters in single query.

My query was this:

$mongoDb = MongoDbConnector::getCollection("endusers");
$endUserData = $mongoDb->find(array('active_status' => 1, '$and' => array('active_status' => 2)));

I have to fetch the users whose active_status should be 1 & 2. The above query doesnt seems to work. What is the right one for that?

Thanks on advance for quick response.

Upvotes: 0

Views: 627

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

You have $and the wrong way around. Both arguments need to be included:

$endUserData = $mongoDb->find(array(
   '$and' => array( 
       array( 'active_status' => 1 )
       array( 'active_status' => 2 )
   )
));

And since that would only make sense when looking for both elements within an array element, then you should instead use $all, which is shorter syntax:

$endUserData = $mongoDb->find(array(
    'active_status' => array( '$all' => array(1,2) )
));

I should add that unless you intend to match a document like this:

{ "active_status" => [1,2] }

The you do not in fact want $and at all, but rather you want $or or better yet $in for multiple possible values on the same field:

$endUserData = $mongoDb->find(array(
    'active_status' => array( '$in' => array(1,2) )
));

This matches documents like this:

{ "active_status": 1 },
{ "active_status": 2 }

Upvotes: 1

Related Questions