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

时间:2017-09-13 14:35:30

标签: php mongodb aggregates

我在Mongo Shell中使用此查询来获取数组' events'按照' start'的价值顺序排列字段

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);
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我改变了这一行:

  book_id, xref_type, xref_type_id, xref
  6636551, Fiction, 1, 72771KAM3
  6636551, Non_Fiction, 2, US72771KAM36
  119818569, Fiction, 1, 070185UL5
  119818569, Non_Fiction, 2, US070185UL50
  etc.

进入这个:

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

这是一个身份验证问题。