Php MongoDB aggregation with match and sort order

2.4k views Asked by At

I use this query in Mongo Shell to get the elements of the array 'events' in order by the value of 'start' field

db.collection_name.aggregate(
{ $match: {
    _id : ObjectId("59941bec47582c1e92b93c9b")
}},
{ $unwind: '$events' },   
{ $sort: {
    'events.start': 1
}})

But I don't understand how to do the same thing in php. I have tried to write this without results:

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

I have tried also in this other way:

$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

There are 1 answers

0
AudioBubble On BEST ANSWER

I've found a solution. I have changed this line:

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

into this:

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

That was an authentication problem.