database 在 MongoDB 的 pymongo 中,我如何执行 count()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4415514/
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
In MongoDB's pymongo, how do I do a count()?
提问by TIMEX
for post in db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num):
This is my current code.
这是我目前的代码。
How do I get the count() ?
我如何获得 count() ?
回答by thirtydot
If you're using pymongo version 3.7.0 or higher, see this answerinstead.
如果您使用的是 pymongo 3.7.0 或更高版本,请参阅此答案。
If you want results_count
to ignore your limit()
:
如果你想results_count
忽略你的limit()
:
results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)
results_count = results.count()
for post in results:
If you want the results_count
to be capped at your limit()
, set applySkipLimit
to True
:
如果您希望results_count
将 限制在您的limit()
,请设置applySkipLimit
为True
:
results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)
results_count = results.count(True)
for post in results:
回答by Sohaib Farooqi
Since pymongo version 3.7.0 and above count() is deprecated. Instead use Collection.count_documents
. Running cursor.count
or collection.count
will result in following warning message:
由于 pymongo 3.7.0 及以上版本count() 已弃用。而是使用Collection.count_documents
。运行cursor.count
或collection.count
将导致以下警告消息:
DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
To use count_documents
the code can be adjusted as follows
使用count_documents
代码可以调整如下
import pymongo
db = pymongo.MongoClient()
col = db[DATABASE][COLLECTION]
filter = {"test_set":"abc"}
sort = [("abc",pymongo.DESCENDING)]
skip = 10
limit = 10
doc_count = col.count_documents(filter, skip=skip)
results = col.find(filter).sort(sort).skip(skip).limit(limit)
for doc in result:
//Process Document
Note:count_documents
method performs relatively slow as compared to count
method. In order to optimize you can use collection.estimated_document_count
. This method will return estimated number of docs(as the name suggested) based on collection metadata.
注意:count_documents
与count
方法相比,方法的执行速度相对较慢。为了优化您可以使用collection.estimated_document_count
. 此方法将根据集合元数据返回估计的文档数量(如建议的名称)。
回答by None-da
Not sure why you want the count if you are already passing limit 'num'. Anyway if you want to assert, here is what you should do.
如果您已经通过了限制“num”,不确定为什么要计数。无论如何,如果你想断言,这就是你应该做的。
results = db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num)
results_count = results.count(True)
That will match results_countwith num
这将匹配results_count与num