$sort - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$sort

$sort 集約ステージは、指定されたフィールド値に基づいてパイプライン内のドキュメントを順序付けします。ドキュメントは、指定されたソート基準に従って昇順または降順に並べられます。

パラメータ

  • field: ソートするフィールド名。

  • order: 昇順-1または降順1に使用します。

例 (MongoDB シェル)

次の例は、 $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()