如何使用' $或'从PHP查询MongoDB或者' $和'条款?

时间:2017-04-28 13:33:45

标签: mongodb php-7.1

我希望在过滤器的$or$and子句的帮助下使用MongoDB PHP7.1驱动程序从mongodb获取数据。我试图构建查询来做同样的事情但是没有用。

以下是我的示例代码:

$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;
}

上面的代码给出了以下错误:

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

请帮助我理解我做错了什么。

1 个答案:

答案 0 :(得分:0)

在@Veeram中添加答案:将此作为我的过滤器,它不起作用:

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

按照@Veeram的建议添加了额外的[]。此配置适用于$and

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