EDIT: While this was true in 2014, modern versions of pymongo and MongoDB have changed this behaviour. Buyer beware:
.count()
是查找查询中返回的结果数的正确方法.count()
方法不会耗尽游标的迭代器,因此在迭代结果集中的项之前,可以安全地进行.count()
次判断.
MongoDB 2.4中的计数方法的性能得到了极大的改进.唯一能让你的count
变慢的事情就是查询是否有索引集.要确定查询中是否有索引,可以执行以下操作
query = collection.find({"string": field})
print query.explain()
如果在结果中看到BasicCursor
,则需要在string
字段中为该查询创建索引.
EDIT:正如@alvapan指出的,pymongo 3.7+中的pymongo deprecated this方法现在更倾向于在单独的查询中使用count_documents
.
item_count = collection.count_documents({"string": field})
计算查询返回的项数的正确方法是,在迭代查询后判断查询上的.retreived
计数器,或者首先判断查询:
# Using .retrieved
query = collection.find({"string": field})
for item in query:
print(item)
print('Located {0:,} item(s)'.format(query.retrieved))
或者,换一种方式:
# Using the built-in enumerate
query = collection.find({"string": field})
for index, item in enumerate(query):
print(item)
print('Located {0:,} item(s)'.format(index+1))