Php 未捕获异常“MongoDB\Driver\exception\RuntimeException”,消息为“表示表达式的对象必须只有一个字段:
我写了下面几行代码Php 未捕获异常“MongoDB\Driver\exception\RuntimeException”,消息为“表示表达式的对象必须只有一个字段:,php,mongodb,aggregation-framework,mongodb-php,Php,Mongodb,Aggregation Framework,Mongodb Php,我写了下面几行代码 $cursor = $this->collection->aggregate(array( array( '$match' => array( "_id" => new MongoDB\BSON\ObjectID($this->id) )
$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”,其中包含消息“表示表达式的对象必须只有一个字段:
请帮忙 只是缺少数组符号并在一些错误的位置进行匹配:
$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是否与文档中的示例相匹配。在$lt和$eq上缺少包装数组,在$and和$filter条件中缺少包装数组。PHP认为这是{$and:{$lt:[…],$eq:[…]},当您需要{$and:[{$lt:[…]},{$eq:[…]}时。请记住,任何带有=>意味着{}的东西都是隐含的,如果没有它,那么它就是[]。你能在示例中显示一下吗?我试过像“$和”=>array数组“$lt”=>array“$$allot.ToDate”,new MongoDB\BSON\UTCDateTimenew DateTime->getTimestamp*1000,数组“$eq”=>数组“$$allocation.RoomId”,$this->RoomId。。。。。。。。。它不起作用请在代码段中显示为答案