首页 文章

如何通过新的PHP pecl / mongodb驱动程序(1.1.2)和库使用MongoDB组功能

提问于
浏览
2

新司机:https://github.com/mongodb/mongo-php-driver

新图书馆:https://github.com/mongodb/mongo-php-library

我已成功选择了集合,列出了字段,设置了订单并使用了限制/跳过 .

可以在库的测试中找到此语法的示例:https://github.com/mongodb/mongo-php-library/blob/master/tests/Collection/CrudSpec/FindFunctionalTest.php

但是,我很难找到如何通过PHP库使用Mongos分组函数的任何文档或语法示例 .

我可以在MongoDB中找到大量如何直接执行此操作的示例,以及之前的驱动程序和库“聚合”类,但不能通过此新库找到 .

2 回答

  • 2

    似乎新的 $collection->find() 函数$ options数组不接受组参数(与sort, limit and batch size as per tests不同) .

    似乎没有对PHP库中的分组进行任何测试,但我现在使用MongoDB\Collection::aggregate() method,它使用与传统驱动程序类似的语法 .

    示例语法:

    <?php
    $group_pipeline = [
        '$group' => [
            '_id' => [ 'event_type' => '$_id.eT' ],
            'total' => ['$sum' => 1 ],
        ],
    ];
    $aggregation = $collection->aggregate([
        $match_pipeline,
        $group_pipeline,
        $sort_pipeline,
    ]);
    
  • 0

    旧驱动程序中的组方法仅仅是"group"命令的快捷方式 . 新的驱动程序(和库)没有方法,但您仍然可以自己运行group命令 . 我们正在跟踪https://jira.mongodb.org/browse/PHPLIB-177中这个助手的添加情况 .

    聚合 $group 是类似的,可能是推荐的,因为它不通过JavaScript . 我们的文档说明了这一点:

    因为db.collection.group()使用JavaScript,所以它受到许多性能限制 . 对于大多数情况,聚合管道中的$ group运算符提供了一个具有较少限制的合适替代方案 .

    原始组命令仍可以使用以下命令运行:

    $ns = "databasename.collectionname";
    $cmd = new \MongoDB\Driver\Command( [
        'group' => [
            'ns' => $ns,
            'key' => $key, // (or '$keyf' if you're passing in a MongoCode object)
            '$reduce' => $reduce,
            'cond' => $cond, // optional, and "condition" option in the old driver
            'finalize' => $finalize, // optional
        ]
    ] );
    
    $manager->executeCommand( $ns, $cmd );
    

    $manager 可以与新扩展一起使用,但新库尚无法访问它(在https://jira.mongodb.org/browse/PHPLIB-186中跟踪)

相关问题