View a markdown version of this page

$sortArray - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$sortArray

8.0 版的新增内容

弹性集群不支持。

Amazon DocumentDB 中的$sortArray运算符对数组的元素进行排序。对于标量值数组,数组按元素值排序。对于文档数组,数组按指定的一个或多个字段排序。运算符按升序 (1) 或降序 () 返回排序后的数组。-1

注意

$sortArray在查询计划器版本 3 的聚合管道$project阶段支持。

语法

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

参数

  • input: 要排序的数组。

  • sortBy: 排序顺序。对于标量值数组,请指定1升序或降序-1。对于文档数组,请指定要作为排序依据的表单文档{ field: 1 }{ field: -1 }每个字段。

示例(MongoDB 外壳)

以下示例演示如何使用$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()