2

I want to get data from mongodb by using MongoDB PHP7.1 Driver with the help of $or or $and clause in filter. I have tried to construct query to do the same but that didn't work.

Here is my sample code here:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

try {
   $filter = [
        '$or'  => [
          'age' => [ '$gt' => 40],
          'name' => 'abc'
        ]
      ];
   $query = new MongoDB\Driver\Query($filter);

   $rows = $manager->executeQuery("test.users", $query);


   foreach ($rows as $key => $val) {
      print_r($val);
   }
} catch(MongoDB\Driver\Exception $e) {
   echo $e->getMessage(), "\n";
   exit;
}

The above code gives me below error:

Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: $or must 
be an array in C:\xampp\htdocs\local\demo.php:50 Stack trace: #0 
C:\xampp\htdocs\local\demo.php(50): MongoDB\Driver\Manager-
>executeQuery('test.users', Object(MongoDB\Driver\Query)) #1 {main} thrown 
in C:\xampp\htdocs\local\demo.php on line 50

Please help me to understand what I am doing wrong.

3
  • 2
    You will need a second expression for $or. Try $filter = [ 'name' => 'abc', '$or' => [[ 'age' => [ '$gt' => 40] ], second expression goes here] ]; Commented Apr 28, 2017 at 13:43
  • @Veeram thank you it's worked. I had forgot to add that internal array bracket to every condition. Commented Apr 28, 2017 at 13:49
  • @Veeram -- many thanks! worked for $and the same. Commented Aug 25, 2018 at 5:08

2 Answers 2

4

Adding to answer from @Veeram: Had this as my filter, which did not work:

$filter  = [
    '$and' =>
        ['date' => ['$gte' => $start_date]],
        ['date' => ['$lte' => $end_date]]
];

added the extra [] as @Veeram suggested. This configuration works for $and:

$filter  = [
    '$and' => [
        ['date' => ['$gte' => $start_date]],
        ['date' => ['$lte' => $end_date]]
    ]
];
Sign up to request clarification or add additional context in comments.

Comments

0

you can do this also

$result=$collections->
find(array('$and=>array(array('date'=>array('$gte'=>$start_date)
),array('date'=>array('$lte'=>$end_date))));

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.