简体   繁体   English

如何在python中限制mongo查询

[英]How to limit mongo query in python

I am trying to retrieve data from mongodb with python. 我试图用python从mongodb中检索数据。 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. 我正在使用pymongo驱动程序。 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'}

As specified in this question , indexed access will ignore the limit . 如此问题中所述 ,索引访问将忽略该limit And count() does not obey limit or skip by default as explained the manual . 并且count()不遵守限制或默认跳过,如手册中所述 You can pass with_limit_and_skip=True to make count() work with limit. 您可以传递with_limit_and_skip=True以使count()与限制一起使用。

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

db.myusers.find(limit=2)

如果要应用某些条件,可以使用db.myusers.find({query}, limit=2)并计算结果数,请使用db.myusers.find({query}, limit=2).count()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM