我编写了以下函数来花费一段时间,并使用pymongo软件包在mongo中运行搜索后,将结果返回给主程序:
def searchMsgByDate (mycol,option):
dt = date.today()
if option == "today":
start = datetime.combine(dt, datetime.min.time())
end = datetime.combine(dt, datetime.max.time())
elif option == "yesterday":
start = datetime.combine(dt, datetime.min.time()) - timedelta(days=1)
end = datetime.combine(dt, datetime.max.time()) - timedelta(days=1)
elif option == "week":
start = datetime.combine( dt - timedelta(days=dt.weekday()), datetime.min.time())
end = datetime.combine(dt, datetime.max.time())
elif option == "month":
start = datetime.combine( dt - relativedelta(day=1) , datetime.min.time())
end = datetime.combine(dt, datetime.max.time())
elif option == "year":
start = datetime.combine( dt - relativedelta(month=1,day=1) , datetime.min.time())
end = datetime.combine(dt, datetime.max.time())
elif option == "forever":
start = datetime.combine( date(1970, 1, 1) , datetime.min.time())
end = datetime.combine(dt, datetime.max.time())
else:
print("Invalid option for searchMsgMain; exiting")
result = mycol.find({"msg_date": { "$gte": start, "$lt": end}});
record_count = 0
for entry in result:
record_count = record_count + 1
if record_count > 0:
print ("Records found =", record_count)
else:
print ("No records found")
return result
这是调用该函数的主程序:
out = searchMsgByDate(mycol)
for entry in out:
....
....
这样做时,主程序中什么也没发生。我可以确认函数中的搜索结果给出了超过90条记录
我认为我在返回此类对象时做错了,否则无法实现。我能够成功返回简单值。
任何想法都值得赞赏。
答案 0 :(得分:0)
我将结果写入数组,并在函数返回时将其发送回去。效果很好。
mongo_query = mycol.find({"msg_date": { "$gte": start, "$lt": end}});
record_count = 0
result = []
for entry in mongo_query:
result.append(entry)
record_count = record_count + 1
if record_count == 0:
print ("No records found")
return result
答案 1 :(得分:0)
1)您不必通过遍历游标元素来独自执行计数。相反,您可以调用db.collection.find({})。count()方法。可以找到文档here
2)我不确定myCol是什么,但是它应该是MongoClient.database_name对象。例如,考虑以下代码片段:
console.log(formData.get('file'));
如您所见,我初始化了MongoClient,在这种情况下,数据库名称为KKNY。从这一点开始,我可以通过运行from pymongo import MongoClient
class Events:
def __init__(self):
self.client = MongoClient('localhost', 27017)
self.database = self.client.KKNY
def retrieveEvents(self):
event_names = self.database['event_names']
return event_names.find({})
访问该数据库中的集合。
3)还请包括从现在开始用于pymongo的版本,它将使我们的生活更轻松