Python MongoDB 限制
在检索一个集合的内容时,你可以使用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'}