(無版本資訊,可能僅在 Git 中)
CollectionFind::sort — 設定排序條件
根據 sort_expr 參數中選擇的欄位排序結果集。允許的排序方式為 ASC(升序)或 DESC(降序)。此操作等同於 SQL 的「ORDER BY」操作,並遵循相同的規則。
sort_expr
可以提供一個或多個排序表達式。評估順序是從左到右,每個表達式之間用逗號分隔。
一個 CollectionFind 物件,可用於執行命令或新增其他操作。
範例 #1 mysql_xdevapi\CollectionFind::sort() 範例
<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find()
->sort('job desc', 'age asc')
->execute();
var_dump($result->fetchAll());
?>
上述範例將輸出類似以下的內容
array(2) { [0]=> array(4) { ["_id"]=> string(28) "00005b6b53610000000000000106" ["age"]=> int(18) ["job"]=> string(6) "Butler" ["name"]=> string(6) "Alfred" } [1]=> array(4) { ["_id"]=> string(28) "00005b6b53610000000000000107" ["age"]=> int(42) ["job"]=> string(6) "Butler" ["name"]=> string(8) "Reginald" } }