$natural - Amazon DocumentDB

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

$natural

Amazon DocumentDB 中的$natural运算符用于按自然顺序对文档进行排序,也就是文档在集合中的插入顺序。这与默认的排序行为形成鲜明对比,默认排序行为是根据指定字段的值对文档进行排序。

参数

示例(MongoDB 外壳)

以下示例演示如何使用$natural运算符按自然顺序对集合中的文档进行排序。

创建示例文档

db.people.insertMany([ { "_id": 1, "name": "María García", "age": 28 }, { "_id": 2, "name": "Arnav Desai", "age": 32 }, { "_id": 3, "name": "Li Juan", "age": 25 }, { "_id": 4, "name": "Carlos Salazar", "age": 41 }, { "_id": 5, "name": "Sofia Martínez", "age": 35 } ]);

查询示例

db.people.find({}, { "_id": 1, "name": 1 }).sort({ "$natural": 1 });

输出

[ { "_id": 1, "name": "María García" }, { "_id": 2, "name": "Arnav Desai" }, { "_id": 3, "name": "Li Juan" }, { "_id": 4, "name": "Carlos Salazar" }, { "_id": 5, "name": "Sofia Martínez" } ]

该查询按自然顺序(即插入顺序)对集合中的文档进行排序。

代码示例

要查看使用该$natural命令的代码示例,请选择要使用的语言的选项卡:

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('people'); const documents = await collection.find({}, { projection: { _id: 1, name: 1 } }) .sort({ $natural: 1 }) .toArray(); console.log(documents); 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['people'] documents = list(collection.find({}, {'_id': 1, 'name': 1}).sort('$natural', 1)) print(documents) client.close() example()