Python MongoDB –限制查询limit用法介绍

2021年3月9日15:57:49 发表评论 979 次浏览

MongoDB是最常用的数据库之一, 其文档存储为集合。可以将这些文档与JSON对象进行比较。 MongoDB与Python一起使用时, 该组合称为PyMongo.

limit()

函数limit()顾名思义-限制将要返回的文档数量。参数中只有一个参数, 它是一个数字, 表示需要返回的文档数。

语法如下:

coll.find().limit(n)

其中

  • coll-馆藏名称
  • n-需要返回的号码

范例1:

样本数据库:

python-mongodb-sample-database2
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)

输出如下:

集合中的前3个文档是:{'_id':1, 'name':'Vishwash', 'Roll No':'1001', 'Branch':'CSE'} {'_id':2, 2, 'name' :'Vishesh', 'Roll No':'1002', 'Branch':'IT'} {'_id':3, 'name':'Shivam', 'Roll No':'1003', 'Branch': '我'}

而限制()限制了获取的文档数量, 可以根据某些指定条件使用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, "名称":"洗碗", "滚动编号":" 1001", "分支":" CSE"}

用于在获取所述数量的文档之前跳过某些文件跳跃()可以与限制()

范例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个文档是:{'_id':3, 'name':'Shivam', 'Roll No':'1003', 'Branch':'ME'} {'_id':4, 4, 'name': 'Yash', 'Roll No':'1004', 'Branch':'ECE'} {'_id':5, 'name':'Raju', 'Roll No':'1005', 'Branch':' CSE'}

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: