2

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);
}
2
  • Your query looks okay. Please consider adding sample documents that you are expecting query to return. Verify if you are connected to correct mongo server & db with right permissions by running simple find query. Commented Sep 13, 2017 at 17:21
  • yes, thank you. With the second code there was an authentication problem. I have added the db name in the connection url now. Commented Sep 13, 2017 at 18:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.