View a markdown version of this page

$sortArray - Amazon DocumentDB

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

$sortArray

8.0 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB 中的$sortArray運算子會排序陣列的元素。對於純量值的陣列,陣列會依元素值排序。對於文件陣列,陣列會依指定的欄位排序。運算子會以遞增 (1) 或遞減 (-1) 順序傳回排序的陣列。

注意

$sortArray 在具有查詢規劃器第 3 版的彙總管道$project階段中支援 。

語法

{ $sortArray: { input: <array>, sortBy: <sort specification> } }

參數

  • input:要排序的陣列。

  • sortBy:排序順序。對於純量值陣列,1請為遞增或遞-1減指定 。對於文件陣列,{ field: -1 }請指定格式的文件{ field: 1 }或要排序的每個欄位。

範例 (MongoDB Shell)

下列範例示範如何使用 $sortArray運算子,以遞增順序排序陣列的元素。

建立範例文件

db.miles.insertMany([ { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]}, { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780]}, { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880]} ]);

查詢範例

db.miles.aggregate([ { $project: { _id: 1, member_since: 1, credit_card: 1, sorted_flight_miles: { $sortArray: { input: "$flight_miles", sortBy: 1 } } } } ]);

輸出

{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "sorted_flight_miles" : [ 880, 1205, 2560 ] } { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "sorted_flight_miles" : [ 890, 1205, 2560, 2780 ] } { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "sorted_flight_miles" : [ 880, 1205 ] }

在此範例中,$sortArray運算子會以遞增順序排序flight_miles陣列。輸出中產生的sorted_flight_miles欄位會以排序順序顯示陣列的元素。

程式碼範例

若要檢視使用 $sortArray命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js

以下是在 Node.js 應用程式中使用 $sortArray 運算子的範例:

const { MongoClient } = require('mongodb'); async function sortArray() { 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('miles'); const result = await collection.aggregate([ { $project: { _id: 1, member_since: 1, credit_card: 1, sorted_flight_miles: { $sortArray: { input: '$flight_miles', sortBy: 1 } } } } ]).toArray(); console.log(result); client.close(); } sortArray();
Python

以下是在 Python 應用程式中使用 $sortArray 運算子的範例:

from pymongo import MongoClient def sort_array(): 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.miles result = list(collection.aggregate([ { '$project': { '_id': 1, 'member_since': 1, 'credit_card': 1, 'sorted_flight_miles': { '$sortArray': { 'input': '$flight_miles', 'sortBy': 1 } } } } ])) print(result) client.close() sort_array()