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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:58:00  来源:igfitidea点击:

In MongoDB's pymongo, how do I do a count()?

mongodbcountpymongodatabase

提问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_countto 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_countto be capped at your limit(), set applySkipLimitto True:

如果您希望results_count将 限制在您的limit(),请设置applySkipLimitTrue

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.countor collection.countwill result in following warning message:

由于 pymongo 3.7.0 及以上版本count() 已弃用。而是使用Collection.count_documents。运行cursor.countcollection.count将导致以下警告消息:

DeprecationWarning: count is deprecated. Use Collection.count_documents instead.

To use count_documentsthe 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_documentsmethod performs relatively slow as compared to countmethod. 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_documentscount方法相比,方法的执行速度相对较慢。为了优化您可以使用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_countnum