MongoDb v4.2.1聚合-如何在PHP 7代码中使用Join

我正在使用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 
wuyangsunyu 回答:MongoDb v4.2.1聚合-如何在PHP 7代码中使用Join

好,我得到了答案:

我添加了以下行:'cursor'=> new stdClass

<?php
//mongo database join example
    public function test_join() {

        global $mng;
        global $dbname;


        $pipeline =  [['$lookup' => ["from" => "items","localField" => "items","foreignField" => "items","as" => "fromItems"]]];

        $aggregate = new \MongoDB\Driver\Command([
           'aggregate' => 'orders','cursor' => new stdClass,'pipeline' => $pipeline
        ]);

        $cursor = $mng->executeCommand($dbname,$aggregate);
        return $cursor;

    }

?>

现在,我可以得到结果了。

本文链接:https://www.f2er.com/2994439.html

大家都在问