【问题标题】:Get amount of objects saved in MongoDB using Pymongo使用 Pymongo 获取保存在 MongoDB 中的对象数量
【发布时间】:2022-12-16 11:44:28
【问题描述】:

我正在尝试获取保存在 MongoDB 中的对象数量

db = myclient.database_sample
my_collection = db["database"]


mydoc = my_collection.find().count()
print("The number of documents in collection : ", mydoc)

但我收到一个错误

mydoc = my_collection.find().count()
AttributeError: 'Cursor' object has no attribute 'count'

我正在使用 Pymongo 2.0

【问题讨论】:

    标签: python mongodb


    【解决方案1】:

    pymongo 的find() 函数返回一个游标对象(不是数组)。 Pymongo 确实包含一个count_documents function。意思是代码应该是这样的:

    numberOfDocs = my_collection.count_documents({})
    

    编辑:更新为正确的解决方案。

    【讨论】:

    • 它返回一个 TypeError: object of type 'Cursor' has no len()
    • 事实证明 find() 返回一个 Cursor 对象,而不是一个数组(这解释了“类型为“Cursor”的对象”错误。根据 pymongo 的文档,有一个计数文档函数 my_collection.find().count_documents({} ). 将更新上面的解决方案。
    【解决方案2】:

    如果您想继续使用 .find() 方法,则需要将其转换为列表:

    numberOfDocs = len(list(my_collection.find()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-15
      • 2017-01-13
      • 2018-05-17
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多