【发布时间】:2023-03-06 16:07:01
【问题描述】:
我正在使用 MongoDB 4.2 开发 PHP7。
我正在尝试使用聚合连接表。
我可以在 mongo 控制台上进行操作。
db.orders.aggregate([
{
$lookup: {
from: "items",
localField: "item", // field in the orders collection
foreignField: "item", // field in the items collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
])
得到结果:
{ "_id" : 1, "item" : "almonds", "description" : "almond clusters", "instock" : 120, "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "pecans", "description" : "candied pecans", "instock" : 60, "price" : 20, "quantity" : 1 }
我想在 PHP 中做同样的事情,但没有得到结果:
我的 PHP 代码是:
<?php
public function demo_join() {
global $mng; // $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
global $dbname;
$command = new MongoDB\Driver\Command([
'aggregate' => 'orders',
'pipeline' => [
['$lookup' => ["from" => "items","localField" => "items","foreignField" => "items","as" => "fromItems"]],
],
]);
//$cursor = $mng->executeCommand($dbname, $command);
try {
$cursor = $manager->executeCommand($dbname, $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
return $cursor;
}
?>
并收到此错误:
Uncaught Error: Call to a member function executeCommand() on null in $cursor = $manager->executeCommand($dbname, $command);
还有一段时间
Uncaught MongoDB\Driver\Exception\CommandException: The 'cursor' option is required, except for aggregate with the explain argument in
【问题讨论】: