【问题标题】:How to query MongoDB from PHP using '$or' or '$and' clause?如何使用 '$or' 或 '$and' 子句从 PHP 查询 MongoDB?
【发布时间】:2017-09-26 15:35:34
【问题描述】:

我想通过过滤器中的$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

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

【问题讨论】:

  • $or 需要第二个表达式。试试$filter = [ 'name' => 'abc', '$or' => [[ 'age' => [ '$gt' => 40] ], second expression goes here] ];
  • @Veeram 谢谢你成功了。我忘了在每个条件中添加那个内部数组括号。
  • @Veeram -- 非常感谢!为$and 工作过。

标签: mongodb php-7.1


【解决方案1】:

添加来自@Veeram 的回答:将此作为我的过滤器,但不起作用:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多