📜  Python MongoDB-限制

📅  最后修改于: 2020-11-07 09:02:55             🧑  作者: Mango


检索集合的内容时,可以使用limit()方法限制结果中的文档数。此方法接受一个数字值,该值表示结果中所需的文档数。

句法

以下是limit()方法的语法-

>db.COLLECTION_NAME.find().limit(NUMBER)

假设我们已经创建了一个集合,并向其中插入了5个文档,如下所示-

> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
   ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
   ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
   ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
   ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
   ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
   ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 6,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

下一行检索集合的前3个文档。

> db.sample.find().limit(3)
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }

使用Python限制文档

为了将查询结果限制为特定数量的文档,pymongo提供了limit()方法。向此方法传递一个数字值,该值表示结果中所需的文档数。

以下示例检索集合中的前三个文档。

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['l']

#Creating a collection
coll = db['myColl']

#Inserting document into a collection
data = [
   {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
   {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
   {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
   {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")

#Retrieving first 3 documents using the find() and limit() methods
print("First 3 documents in the collection: ")

for doc1 in coll.find().limit(3):
   print(doc1)

输出

Data inserted ......
First 3 documents in the collection:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}