45

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'}
Mulagala
  • 8,231
  • 11
  • 29
  • 48
  • 1
    Have you tried [**`db.myusers.find()[0:2]`**](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.__getitem__)? This will return this cursor with a limit of 2 and skip of 0 applied. – chridam Apr 13 '15 at 11:52
  • 1
    duplicate of http://stackoverflow.com/q/14712402/2327328 – philshem Apr 13 '15 at 11:53
  • @ForceBru, Ya tried but still getting all the values – Mulagala Apr 13 '15 at 11:54
  • @philshem, I have gone through that link dear.But i din't get the solution. – Mulagala Apr 13 '15 at 11:55
  • Please post more code. `limit` is supposed to work in this way. There might be problem in somewhere else. – taskinoor Apr 13 '15 at 12:02

2 Answers2

56

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
Community
  • 1
  • 1
taskinoor
  • 45,586
  • 12
  • 116
  • 142
10

db.myusers.find(limit=2)

If you want to apply some condition, you can use db.myusers.find({query}, limit=2) and to count the number of results, use db.myusers.find({query}, limit=2).count()

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Jyothsna Gadde
  • 175
  • 1
  • 7