$自然 - Amazon DocumentDB

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

$自然

Amazon DocumentDB 中的$natural運算子用於依其自然順序排序文件,這是它們插入集合的順序。這與預設排序行為相反,也就是根據指定欄位的值排序文件。

參數

範例 (MongoDB Shell)

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