View a markdown version of this page

$sort - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$sort

$sort 彙總階段會根據指定的欄位值來排序管道中的文件。文件會根據提供的排序條件,以遞增或遞減順序排列。

參數

  • field:要排序的欄位名稱。

  • order:1用於遞增順序或用於-1遞減順序。

範例 (MongoDB Shell)

下列範例示範如何使用 $sort階段,依價格以遞減順序訂購產品。

建立範例文件

db.products.insertMany([ { _id: 1, name: "Laptop", category: "Electronics", price: 1200 }, { _id: 2, name: "Mouse", category: "Electronics", price: 25 }, { _id: 3, name: "Desk", category: "Furniture", price: 350 }, { _id: 4, name: "Chair", category: "Furniture", price: 150 }, { _id: 5, name: "Monitor", category: "Electronics", price: 400 } ]);

查詢範例

db.products.aggregate([ { $sort: { price: -1 } } ]);

輸出

[ { _id: 1, name: 'Laptop', category: 'Electronics', price: 1200 }, { _id: 5, name: 'Monitor', category: 'Electronics', price: 400 }, { _id: 3, name: 'Desk', category: 'Furniture', price: 350 }, { _id: 4, name: 'Chair', category: 'Furniture', price: 150 }, { _id: 2, name: 'Mouse', category: 'Electronics', price: 25 } ]

程式碼範例

若要檢視使用$sort彙總階段的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('products'); const result = await collection.aggregate([ { $sort: { price: -1 } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['products'] result = list(collection.aggregate([ { '$sort': { 'price': -1 } } ])) print(result) client.close() example()

增量排序

增量排序是一種最佳化,其中 Amazon DocumentDB 使用已排序多欄位排序領導欄位的索引。然後,Amazon DocumentDB 只會排序每個文件群組中共用相同前導值的剩餘欄位。Amazon DocumentDB 不會將記憶體中的整個結果集排序為一個區塊 (完整排序),而是以索引順序讀取文件。然後,它會執行許多小型、獨立的排序,每個群組一個。結果與完整排序相同。只有查詢計畫及其使用變更的記憶體和工作量。

優勢

增量排序提供下列優點:

  • 記憶體使用量較低,磁碟型排序溢出較少。Amazon DocumentDB 一次訂購一個小群組,而不是一次整個結果集。

  • 使用 加快結果速度limit。Amazon DocumentDB 可以在讀取整個輸入之前發出排序的文件。排序後面接著 limit(例如 top-N 或分頁查詢) 可在產生足夠的文件時立即停止。

當 Amazon DocumentDB 選擇增量排序時

例如,假設 上的排序{ customerId: 1, orderDate: -1 }和 上的索引{ customerId: 1 },則索引已傳回 排序的文件customerId。Amazon DocumentDB 只需要排序customerId由 共用相同的每個文件群組orderDate。已排序的前導欄位 (customerId) 是預先排序的金鑰。根據索引已提供的排序數量,Amazon DocumentDB 會選擇三種行為之一:

  • 索引會排序每個排序索引鍵。不需要排序。Amazon DocumentDB 會依請求的順序直接讀取文件。

  • 索引會排序排序索引鍵的前綴。Amazon DocumentDB 使用增量排序,只排序每個預先排序群組中的結尾索引鍵。

  • 沒有索引會排序任何前置排序索引鍵。Amazon DocumentDB 會對整個輸入執行完整排序。

需求和限制

增量排序需要執行規劃器 3.0 版的 Amazon DocumentDB 8.0.2 或更新版本 (Amazon DocumentDB 8.0.2 版的預設查詢規劃器)。如需規劃器版本的詳細資訊,請參閱 查詢規劃器 v3。

Amazon DocumentDB 無法使用部分索引或多索引鍵 (陣列) 索引為增量排序提供預先排序的字首。在這些情況下,Amazon DocumentDB 會回到完整排序。這絕不會影響結果的正確性。

使用 驗證增量排序 explain()

使用 explain() 確認查詢使用增量排序。在獲勝計劃中,增量排序會顯示為SORT階段,其中包含presortedKeys陣列,列出索引已排序的前導排序欄位。完整排序會顯示為沒有presortedKeys陣列的SORT階段。presortedKeys 欄位是explain()輸出的 Amazon DocumentDB 特定新增項目,不會顯示在 MongoDB 解釋計劃中。

db.orders.createIndex({ customerId: 1 }) db.orders.find({}).sort({ customerId: 1, orderDate: -1 }).explain()
{ "stage": "SORT", "sortPattern": { "customerId": 1, "orderDate": -1 }, "presortedKeys": [ "customerId" ], "inputStage": { "stage": "IXSCAN", "indexName": "customerId_1", "direction": "forward" } }