【问题标题】:Get number of documents returned from a query获取查询返回的文档数
【发布时间】:2019-05-16 20:50:31
【问题描述】:

似乎找不到能回答我的问题的答案。

我有一系列 MongoDB 文档,其中包含版本号,包括分代和增量版本(例如 1.2、1.4.2 等)。

搜索数据库的代码是:

client = MongoClient("Localhost",27017)             # Set Mongo Client to local hose

db = client.Assignment                              # Set db as the DB required
collection = db.project                             # Set the collection to the collection required

Version = float(input("Enter version number:   "))

query = {"prod.v_num": Version}

Return = collection.find(query)

for doc in Return:
    print(doc["_id"], "¦", doc["prod"]["name"], "¦", doc["prod"]["v_num"], "¦",doc["owner"])

但是,有时搜索没有返回结果(即没有具有所需版本号的文档)。

我如何确定是否没有与退货相符的文件,并允许我打印出警告信息?

我试过了,但是没用

if len(Return) == 0:
    print("No documents match your search").

【问题讨论】:

    标签: python mongodb mongodb-query pymongo


    【解决方案1】:

    pymongo.cursor.Cursor 没有实现__len__ 方法。这就是您收到此错误的原因:

    TypeError: 'Cursor' 类型的对象没有 len()

    但它实现了count 方法,该方法返回此查询结果集中的文档数。你可以这样使用它:

    if Return.count() == 0:
        print("No documents match your search")
    

    另请注意,它自 Python3.7 版本以来已被弃用,您应该改用 count_documents 查询:

    Return = collection.count_documents(query)
    if Return == 0:
        print("No documents match your search")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多