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").
解决方案
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")