获取查询返回的文档数

2024-04-19 00:18:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一系列包含版本号的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").

Tags: theto文档clientdbdocreturnversion
1条回答
网友
1楼 · 发布于 2024-04-19 00:18:57

pymongo.cursor.Cursor不实现__len__方法。这就是为什么会出现这样的错误:

TypeError: object of type 'Cursor' has no len()

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

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

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

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

相关问题 更多 >