$limit - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$limit

Amazon DocumentDB の $limit演算子は、クエリによって返されるドキュメントの数を制限するために使用されます。これは MongoDB $limit演算子に似ていますが、Amazon DocumentDB で使用する場合の具体的な考慮事項がいくつかあります。

Amazon DocumentDB では、 $limit演算子は、一致するドキュメントの合計のサブセットを取得するページ分割に役立ちます。これにより、各レスポンスで返されるドキュメントの数を制御できるため、パフォーマンスが向上し、ネットワーク経由で転送されるデータ量が減ります。

パラメータ

  • limit: 返されるドキュメントの最大数。これは負以外の整数値である必要があります。

例 (MongoDB シェル)

次の例は、 $limit演算子を使用して、指定されたフィルターに一致する最大 1 つのドキュメントを返す方法を示しています。

サンプルドキュメントを作成する

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()