【问题标题】:MongoDb v4.2.1 aggregation - How to use join in php 7 codeMongoDb v4.2.1 聚合 - 如何在 php 7 代码中使用 join
【发布时间】: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 

【问题讨论】:

    标签: mongodb php-7.2


    【解决方案1】:

    好的,我得到了答案:

    我添加了这一行:'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;
    
        }
    
    ?>
    

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

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      相关资源
      最近更新 更多