$limit - Amazon DocumentDB

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

$limit

Amazon DocumentDB 中的$limit運算子用於限制查詢傳回的文件數量。它類似於 MongoDB $limit運算子,但在搭配 Amazon DocumentDB 使用它時有一些特定的考量。

在 Amazon DocumentDB 中,$limit運算子對於分頁很有用,您想要擷取相符文件總數的子集。它可讓您控制每個回應中傳回的文件數量,改善效能並減少透過網路傳輸的資料量。

參數

  • limit:要傳回的文件數量上限。這必須是非負整數值。

範例 (MongoDB Shell)

下列範例示範如何使用 $limit運算子傳回最多一份符合指定篩選條件的文件。

建立範例文件

db.test.insertMany([ { "_id": 1, "star_rating": 4, "comments": "apple is red" }, { "_id": 2, "star_rating": 5, "comments": "comfortable couch" }, { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" }, { "_id": 4, "star_rating": 5, "comments": "this is a great couch" }, { "_id": 5, "star_rating": 5, "comments": "interesting couch" } ]);

查詢範例

db.test.createIndex({ comments: "text" }); db.test.find({ $and: [ { star_rating: 5 }, { $text: { $search: "couch" } } ] }).limit(1);

輸出

[ { _id: 2, star_rating: 5, comments: 'comfortable couch' } ]

程式碼範例

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

Node.js
const { MongoClient } = require('mongodb'); async function limitExample() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('test'); await collection.createIndex({ comments: 'text' }); const query = { $and: [ { star_rating: 5 }, { $text: { $search: "couch" } } ] }; const result = await collection.find(query).limit(1).toArray(); console.log(result); } catch (err) { console.error("Error:", err); } finally { await client.close(); } } limitExample();
Python
from pymongo import MongoClient def limit_example(): try: 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['test'] collection.create_index([('comments', 'text')]) query = { '$and': [ {'star_rating': 5}, {'$text': {'$search': 'couch'}} ] } result = collection.find(query).limit(1) for doc in result: print(doc) except Exception as e: print(f"An error occurred: {e}") finally: client.close() limit_example()