Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit mongo query in python

I am trying to retrieve data from mongodb with python. My db contains lots of data. So I want to limit the data while retrieving. I tried

import datetime from pymongo import Connection connection = Connection('localhost',27017) db = connection['MyWork']   db_data = db.myusers.find().limit(2) #db_data = db.myusers.find()[0:2] print db_data print db_data.count() print db_data[0] print db_data[1] print db_data[2] 

But I am getting more than two documents when I tried above. I am using pymongo driver. How to limit the values

<pymongo.cursor.Cursor object at 0x000000000267D518> 3 {u'age': 24.0, u'_id': ObjectId('552b6e90aad3e2d909d5fb28'), u'place': u'Ravipadu', u'name': u'Shiva'} {u'age': 28.0, u'_id': ObjectId('552b6eabaad3e2d909d5fb29'), u'place': u'Rajahmundry', u'name': u'Anil'} {u'age': 30.0, u'_id': ObjectId('552b6ec1aad3e2d909d5fb2a'), u'place': u'Manchili', u'name': u'Kishore'} 
like image 475
Mulagala Avatar asked Apr 13 '15 11:04

Mulagala


People also ask

How do I limit documents in MongoDB?

The Limit() Method To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

How does limit work in MongoDB?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.

Does MongoDB have a limit?

The maximum size an individual document can be in MongoDB is 16MB with a nested depth of 100 levels. Edit: There is no max size for an individual MongoDB database.


1 Answers

As specified in this question, indexed access will ignore the limit. And count() does not obey limit or skip by default as explained the manual. You can pass with_limit_and_skip=True to make count() work with limit.

print db_data.count(with_limit_and_skip=True) 

Or you can iterate the cursor to see limit in effect.

for data in db.myusers.find().limit(2):     print data 
like image 130
taskinoor Avatar answered Sep 21 '22 20:09

taskinoor