$sort - Amazon DocumentDB

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

$sort

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

參數

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

  • order1用於遞增順序或用於-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()