Python MongoDB – 限制查询
MongoDB 是最常用的数据库之一,其文档存储为集合。这些文档可以与 JSON 对象进行比较。 MongoDB 与Python一起使用时,该组合称为PyMongo 。
限制()
函数limit()
的作用正如其名称所暗示的那样——限制将返回的文档数量。参数中只有一个参数,它是一个数字,表示需要返回的文档数。
句法:
coll.find().limit(n)
在哪里,
- 集合的名称
- n-需要返回的数字
示例 1:
样本数据库:
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Retrieving first 3 documents using the
# find() and limit() methods
print("First 3 docs in the collection are: ")
for doc1 in doc.find().limit(3):
print(doc1)
输出:
First 3 docs in the collection are:
{‘_id’: 1, ‘name’: ‘Vishwash’, ‘Roll No’: ‘1001’, ‘Branch’: ‘CSE’}
{‘_id’: 2, ‘name’: ‘Vishesh’, ‘Roll No’: ‘1002’, ‘Branch’: ‘IT’}
{‘_id’: 3, ‘name’: ‘Shivam’, ‘Roll No’: ‘1003’, ‘Branch’: ‘ME’}
虽然limit()
对获取的文档数量进行了限制,但 find() 可用于根据某些指定标准查找文档。
示例 2:
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Printing documents of only those having
# branch as CSE and limiting the document
# to 1
for doc1 in doc.find({'Branch': 'CSE'}).limit(1):
print(doc1)
输出:
{‘_id’: 1, ‘name’: ‘Vishwash’, ‘Roll No’: ‘1001’, ‘Branch’: ‘CSE’}
为了在获取所述数量的文档之前跳过一些文件, skip()
可以与limit()
一起使用
示例 3:
from pymongo import MongoClient
# Create a pymongo client
client = MongoClient('localhost', 27017)
# database instance
db = client['GFG']
# collection instance
doc = db['Student']
# Retrieving 3 documents using the
# find() and limit() methods
print("3 docs in the collection are: ")
for doc1 in doc.find().limit(3).skip(2):
print(doc1)
输出:
3 docs in the collection are:
{‘_id’: 3, ‘name’: ‘Shivam’, ‘Roll No’: ‘1003’, ‘Branch’: ‘ME’}
{‘_id’: 4, ‘name’: ‘Yash’, ‘Roll No’: ‘1004’, ‘Branch’: ‘ECE’}
{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘CSE’}