【问题标题】:What to use instead of count with Cursor?用什么来代替 Cursor 计数?
【发布时间】:2019-11-28 14:16:11
【问题描述】:

我正在使用find 从数据库中提取数据,并使用count 检查是否存在任何内容(或者是否为空)。 count is deprecated. Use Collection.count_documents instead. 对我大喊大叫,但是当我改变它时,它在说 'Cursor' object has no attribute 'count_documents'。我尝试将collection 添加到db.find(),但仍然没有。

def stuff(x):
    return db['stuffs'].find({"stuff": x})

def check_for_stuff(x):
    things = stuff(x)
    if not things.count():
        return None

【问题讨论】:

  • 发布你想要做的事情。
  • 贴出你目前使用过的代码

标签: python mongodb collections


【解决方案1】:

count_documents 在集合级别工作。因此使用它的适当方法是通过将过滤器直接传递给count_documents 方法来使用db.collection.count_documents({"stuff": x}) 查询数据库。

因此check_for_stuff 可以是:

def check_for_stuff(x):
    count = db['stuffs'].estimated_document_count({"stuff": x}) //or db['stuffs'].count_documents({"stuff": x}) or db.collection.count_documents({"stuff": x}) depending on your use case
    ......Do what you need to do....

使用estimated_document_count 以获得更好的性能。

Here 是您需要进行两次数据库调用的原因

【讨论】:

  • 但我只想调用数据库一次>.> 来查找东西...你是说我必须再次调用它来分别计算相同的东西?
  • 从我在其他地方读到的内容看起来也是这样(检查编辑)
猜你喜欢
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 2018-11-24
  • 2020-01-04
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多