本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$limit
Amazon DocumentDB 中的$limit运算符用于限制查询返回的文档数量。它与 M $limit ongoDB 运算符类似,但是在将其与亚马逊 DocumentDB 一起使用时需要考虑一些特定的注意事项。
在 Amazon DocumentDB 中,$limit运算符对于分页很有用,您想检索所有匹配文档的子集。它允许您控制每次响应中返回的文档数量,从而提高性能并减少通过网络传输的数据量。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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()