1

After hours of experimentations and readings, I cannot find a solution to this problem:

I want to do a MongoDB->find($query) with multiple AND conditions.

For instance, say I want id = 5 and a < 6 and a > 2 and b > 10 and b < 20

I was expecting $query to be:

$query = array("id" => 5,
   "a" => array('$gt' => 2,  
           '$lt' => 6),
   "b" => array('$gt' => 10,
           '$lt' => 20))

But this returns empty results with my DB

I tried various syntaxes such as:

$query = array("id" => 5,
          array( "a" => array('$gt' => 2,
              '$lt' => 6),
       "b" => array('$gt' => 10,
             '$lt' => 20)))

But this fails too.

Also tried with "$AND" variants, no luck.

Is it possible to "mix" several AND conditions in PHP-MongoDB find() requests?

2
  • I'm no SME, but is MondoDB a typo on MongoDB? Commented Mar 21, 2016 at 12:21
  • @MartinCowie Sure, fixed! Thx. Commented Mar 21, 2016 at 13:04

2 Answers 2

4

I've just tested this using MongoDB PHP driver v1.6.11 (PHP-5.5.9). The test data are as below

db.collection.insert({id:5, a:4, b:15})
db.collection.insert({id:9, a:4, b:15})
db.collection.insert({id:5, a:4, b:20})

Using PHP code snippet:

$condition = array(
    '$and' => array(
        array(
            "id" => 5,
            "a" => array('$gt' => 2, '$lt' => 6),
            "b" => array('$gt' => 10, '$lt' => 20)
        )
    )
);
$docs = $coll->find($condition);

foreach( $docs as $o=> $doc) {
    echo json_encode($doc);
}

The above returns only the first document sample. This indicates that $and should work as expected. I've also tested without $and, i.e. :

$condition = array(
                "id" => 5,
                "a" => array('$gt' => 2, '$lt' => 6),
                "b" => array('$gt' => 10, '$lt' => 20)
);

Which also works the same. Try checking your dataset, whether there is a document matching your criteria.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for checking this. I've figured out that the issue was an incorrect type for the values. They were strings instead of float (double). After updating the DB with correct type, it works as expected.
0

This issue is closed: bad value types in the DB (string instead of float/double). Works as expected when updating to correct types in DB.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.