$sort - Amazon DocumentDB

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

$sort

$push運算子搭配使用時,$sort更新修飾詞會訂購陣列元素。它會根據指定的欄位值或元素本身,以遞增或遞減順序排列陣列元素。

參數

  • field:要修改的陣列欄位。

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

範例 (MongoDB Shell)

下列範例示範搭配 $sort 使用修飾詞$push來新增新的測驗分數,並依遞減順序進行排序。

建立範例文件

db.students.insertOne({ _id: 1, name: "Bob", quizzes: [ { score: 85, date: "2024-01-15" }, { score: 92, date: "2024-02-10" } ] });

查詢範例

db.students.updateOne( { _id: 1 }, { $push: { quizzes: { $each: [{ score: 78, date: "2024-03-05" }], $sort: { score: -1 } } } } )

輸出

{ "_id" : 1, "name" : "Bob", "quizzes" : [ { "score" : 92, "date" : "2024-02-10" }, { "score" : 85, "date" : "2024-01-15" }, { "score" : 78, "date" : "2024-03-05" } ] }

程式碼範例

若要檢視使用$sort更新修飾詞的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function updateDocument() { 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('students'); await collection.updateOne( { _id: 1 }, { $push: { quizzes: { $each: [{ score: 78, date: "2024-03-05" }], $sort: { score: -1 } } } } ); const updatedDocument = await collection.findOne({ _id: 1 }); console.log(updatedDocument); await client.close(); } updateDocument();
Python
from pymongo import MongoClient def update_document(): 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.students collection.update_one( {'_id': 1}, { '$push': { 'quizzes': { '$each': [{'score': 78, 'date': '2024-03-05'}], '$sort': {'score': -1} } } } ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()