bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Python/Databases in Python
Python•Databases in Python

Python MongoDB Limit

Limit the Result

To limit the result in MongoDB, we use the limit() method.

The limit() method takes one parameter, a number defining how many documents to return.

Consider you have a "customers" collection:

Customers

{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

Example

Limit the result to only return 5 documents:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
#print the result:
 for x in myresult:
 print(x)

Previous

Python MySQL Limit

Next

Python MySQL Join

This chapter

Overview
23

Lessons

49m

Read time

1. Python MySQL2. Python MongoDB3. Python MySQL Create Database4. Python MongoDB Create Database5. Python MySQL Create Table6. Python MongoDB Create Collection7. Python MySQL Insert Into Table8. Python MongoDB Insert Document9. Python MySQL Select From10. Python MongoDB Find11. Python MySQL Where12. Python MongoDB Query13. Python MySQL Order By14. Python MongoDB Sort15. Python MySQL Delete From By16. Python MongoDB Delete Document17. Python MySQL Drop Table18. Python MongoDB Drop Collection19. Python MySQL Update Table20. Python MongoDB Update21. Python MySQL Limit22. Python MongoDB Limit23. Python MySQL Join

On this page

Limit the ResultCustomers