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

Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' with message 'An object representing an expression must have exactly one field:

我写了如下代码行

         $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();

它正在抛出错误消息“未捕获的异常'MongoDB\Driver\Exception\RuntimeException',消息为'表示表达式的对象必须只有一个字段:“

请帮忙!!!

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

$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 是否与您在文档中看到的示例相匹配。