如何在python中限制mongo查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29604573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit mongo query in python
提问by Mulagala
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
我正在尝试使用 python 从 mongodb 检索数据。我的数据库包含大量数据。所以我想在检索时限制数据。我试过
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
驱动程序。如何限制值
<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'}
采纳答案by taskinoor
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.
如本问题所述,索引访问将忽略limit
. 并且count()
默认情况下不遵守限制或跳过手册中的解释。您可以通过限制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
回答by Jyothsna Gadde
db.myusers.find(limit=2)
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()
如果你想应用一些条件,你可以使用db.myusers.find({query}, limit=2)
和 来计算结果的数量,使用db.myusers.find({query}, limit=2).count()