Php MongoDB 具有匹配和排序顺序的聚合

Php MongoDB aggregation with match and sort order

我在 Mongo Shell 中使用此查询按 'start' 字段

的值顺序获取数组 'events' 的元素
db.collection_name.aggregate(
{ $match: {
    _id : ObjectId("59941bec47582c1e92b93c9b")
}},
{ $unwind: '$events' },   
{ $sort: {
    'events.start': 1
}})

但我不明白如何在 php 中做同样的事情。 我试过写这个没有结果:

$client = new MongoClient("mongodb://admin:$psw@localhost");
$collection = $client->db_name->collection_name;

$cursor = $collection->aggregate([
        ['$match' => ['_id' =>new MongoDB\BSON\ObjectID("59941bec47582c1e92b93c9b")]],
        ['$unwind' => '$events'],
        ['$sort' => ['events.start' => 1]]
]);

foreach($cursor as $document) {
    var_dump($document);
}

我也尝试过其他方式:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017");

$command = new MongoDB\Driver\Command([
    'aggregate' => 'collection_name',
    'pipeline' => [
        ['$match' => ['_id' =>new MongoDB\BSON\ObjectID("59941bec47582c1e92b93c9b")]],
        ['$unwind' => '$events'],
        ['$sort' => ['events.start' => 1]]
    ],
]);
$cursor = $manager->executeCommand('db_name', $command);

foreach($cursor as $key=>$document) {
    var_dump($document);
}

我找到了解决办法。我已经更改了这一行:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017");

进入这个:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017/db_name");

那是身份验证问题。