View a markdown version of this page

$sort - Amazon DocumentDB

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

$sort

$sort聚合阶段根据指定的字段值对管道中的文档进行排序。根据提供的排序标准,文档按升序或降序排列。

参数

  • field:排序依据的字段名称。

  • order:1用于升序或降序-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()

增量排序

增量排序是一种优化,其中 Amazon DocumentDB 使用的索引已经对多字段排序的前导字段进行排序。然后,Amazon DocumentDB 仅对每组文档中具有相同前导值的剩余字段进行排序。Amazon DocumentDB 没有将内存中的整个结果集作为一个块进行排序(完整排序),而是按索引顺序读取文档。然后,它执行许多小的、独立的排序,每组一个。结果与完整排序相同。只有查询计划及其使用的内存量和工作量会发生变化。

优点

增量排序具有以下优点:

  • 减少内存使用量,减少基于磁盘的排序溢出。Amazon DocumentDB 一次订购一个小组,而不是一次订购整个结果集。

  • 使用limit. 更快地获得结果 Amazon DocumentDB 可以在读取全部输入内容之前发出经过排序的文档。在生成足够文档后,排序limit(例如 Top-N 或分页查询)可以立即停止。

当 Amazon DocumentDB 选择增量排序时

例如,给定排序开启{ customerId: 1, orderDate: -1 }且仅开启索引{ customerId: 1 },则索引已经返回排序依据的文档customerId。Amazon DocumentDB 只需要订购共享相同customerId内容的每组文档。orderDate已经排序的前导字段 (customerId) 是预先排序的密钥。根据索引已经提供的种类数量,Amazon DocumentDB 会选择以下三种行为之一:

  • 索引对每个排序键进行排序。不需要排序。亚马逊 DocumentDB 直接按请求的顺序读取文档。

  • 索引对排序键的前导前缀进行排序。Amazon DocumentDB 使用增量排序,仅对每个预先排序的组中的尾随键进行排序。

  • 没有索引对任何前导排序键进行排序。Amazon DocumentDB 对整个输入进行全面排序。

要求和限制

增量排序需要 Amazon DocumentDB 8.0.2 或更高版本,运行计划器版本 3.0(自亚马逊文档数据库 8.0.2 起的默认查询计划器)。有关计划器版本的更多信息,请参阅查询规划器 v3。

Amazon DocumentDB 不能使用部分索引或多键(数组)索引为增量排序提供预排序的前缀。在这些情况下,亚马逊DocumentDB可以完全恢复原状。这永远不会影响结果的正确性。

使用验证增量排序 explain()

explain()用于确认查询是否使用增量排序。在获胜计划中,增量排序作为一个SORT阶段出现,其中包括一个presortedKeys列出索引已排序的前导排序字段的数组。完整排序显示为没有presortedKeys数组的SORT阶段。该presortedKeys字段是亚马逊对explain()输出内容的 DocumentDB-specific 补充,未出现在 MongoDB 解释计划中。

db.orders.createIndex({ customerId: 1 }) db.orders.find({}).sort({ customerId: 1, orderDate: -1 }).explain()
{ "stage": "SORT", "sortPattern": { "customerId": 1, "orderDate": -1 }, "presortedKeys": [ "customerId" ], "inputStage": { "stage": "IXSCAN", "indexName": "customerId_1", "direction": "forward" } }