未捕获的异常'MongoDB \ Driver \ Exception \ RuntimeException',消息'表示表达式的对象必须只有一个字段:

时间:2018-06-12 09:17:06

标签: php mongodb aggregation-framework mongodb-php

我写了如下代码行

         $cursor = $this->collection->aggregate(array(
             array(
                   '$match' => array(
                                "_id" => new MongoDB\BSON\ObjectID($this->id)
                                )
                  ),
             array(
                  '$project' => array(
                  'AllotmentsDetails' => array(
                  '$filter' => array(
                  'input' => '$AllotmentsDetails',
                  'as' => 'allot',
                  'cond' => array(
                   '$and' => array(
                  '$lt' => array('$$allot.ToDate', new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp() * 1000)),
                  '$eq' => array('$$allotment.RoomId', $this->RoomId)
                     )
                   )
                  )
                 ),
                )
              )
            ))->toArray();

它正在抛出错误消息“Uncaught exception'MongoDB \ Driver \ Exception \ RuntimeException',并带有消息'表示表达式的对象必须只有一个字段:”

请帮助!!!

1 个答案:

答案 0 :(得分:1)

只是缺少数组符号并在某些错误的地方匹配:

$pipeline = array(
  array( '$match' => array(
    "_id" => new MongoDB\BSON\ObjectID($this->id)
  )),
  array('$project' => array(
    'AllotmentsDetails' => array(
      '$filter' => array(
        'input' => '$AllotmentsDetails',
        'as' => 'allotment',
        'cond' => array(
          '$and' => array(
            array('$lt' => array(
              '$$allotment.ToDate',
              new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp() * 1000)
            )),
            array('$eq' => array('$$allotment.RoomId', $this->RoomId))
          )
        )
      )
    )
  ))
);

$cursor = $this->collection->aggregate($pipeline)->toArray();

或者因为我们处于现代世界,所以更容易阅读:

$pipeline = [
  ['$match' => [
    "_id" => new MongoDB\BSON\ObjectID($this->id)
  ]],
  ['$project' => [
    'AllotmentsDetails' => [
      '$filter' => [
        'input' => '$AllotmentsDetails',
        'as' => 'allotment',
        'cond' => [
          '$and' => [
            ['$lt' => [
              '$$allotment.ToDate',
              new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp() * 1000)
            ]],
            ['$eq' => ['$$allotment.RoomId', $this->RoomId] ]
          ]
        ]
      ]
    ]
  ]]
];

$cursor = $this->collection->aggregate($pipeline)->toArray();

我建议使用更好的编辑器,并在数据结构上使用json_encode(),以检查生成的JSON是否与文档中的示例匹配。