How to sort data in MongoDB using PHP?

by darrion.kuhn , in category: PHP Databases , a year ago

How to sort data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a year ago

@darrion.kuhn 

To sort data in MongoDB using PHP, you can make use of the sort() function provided by the MongoDB PHP driver. The sort() function takes an array of sorting criteria as its parameter. Here's an example code snippet that demonstrates how to sort data in MongoDB using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

// establish a connection to MongoDB
$mongo = new MongoDBClient("mongodb://localhost:27017");

// select a database and collection
$collection = $mongo->mydb->mycollection;

// define the sorting criteria
$sortCriteria = [
    'age' => 1,     // sort by age in ascending order
    'name' => -1    // then sort by name in descending order
];

// execute the query with sorting
$results = $collection->find([], ['sort' => $sortCriteria]);

// iterate over the results
foreach ($results as $document) {
    var_dump($document);
}


In this example, we connect to a MongoDB instance running on the local machine and select a database and collection. We then define the sorting criteria as an associative array, where the keys represent the field names to sort by and the values represent the sort order (1 for ascending order and -1 for descending order). Finally, we execute a find() query on the collection with the sort option set to the sorting criteria, and iterate over the results.