简体   繁体   English

遍历 mongo cursor 给了我空的结果

[英]Iterating over mongo cursor gives me empty results

I'm using the MongoDB API on Python and was trying to iterate over the results of a query, I know that the find() method returns me a cursor and that I can iterate through it like a list in python. I'm using the MongoDB API on Python and was trying to iterate over the results of a query, I know that the find() method returns me a cursor and that I can iterate through it like a list in python. the code I was running looks like this:我正在运行的代码如下所示:

query_results = mongo_collection.find(query)
emails_dict = {x.get("userId"): x.get("emailAddr") for x in query_results}
send_emails_dict = {x.get("userId"): x.get("sendEmailNotification") for x in query_results}

But for some strange reason both the dictionaries that I'm trying to create are returned as empty, I checked the results of the query and it's not empty, meaning that there are documents in the query_result.但是由于某种奇怪的原因,我试图创建的两个字典都返回为空,我检查了查询的结果,它不是空的,这意味着 query_result 中有文档。 Any clue what's going on?有什么线索吗? Is this a know bug from pymongo?这是来自 pymongo 的已知错误吗?

Try removing for loop and run again尝试删除 for 循环并再次运行

When you run a .find() it returns a cursor which can be iterated.当您运行.find()时,它会返回一个可以迭代的 cursor。

Once you have exhausted the cursor it won't return any further values.一旦你用尽了 cursor 它就不会返回任何进一步的值。 A simple fix in your code (assuming there's not a huge number of records) is to create a list from the cursor:代码中的一个简单修复(假设没有大量记录)是从 cursor 创建一个列表:

query_results = list(mongo_collection.find(query))

Then both the queries should work.然后这两个查询都应该工作。

Alternatively put the query results in a for loop and create the dicts from the resulting record, rather than using the dict comprehension twice.或者将查询结果放在 for 循环中并从结果记录中创建字典,而不是使用字典理解两次。

You could try:你可以试试:

query_results = mongo_collection.find(query)

emails_dict = {}
send_emails_dict = {}

for doc in query_results:
    emails_dict |= {doc["userId"]: doc["emailAddr"]}
    send_emails_dict |= {doc["userId"]: doc["sendEmailNotification"]}

Or perhaps more efficiently:或者也许更有效:

query_results = mongo_collection.find(query)

emails_dict = {}
send_emails_dict = {}

for doc in query_results:
    emails_dict[doc["userId"]] = doc["emailAddr"]
    send_emails_dict[doc["userId"]] = doc["sendEmailNotification"]

Another option is to rewind the cursor:另一种选择是倒带cursor:

query_results = mongo_collection.find(query)
emails_dict = {x.get("userId"): x.get("emailAddr") for x in query_results}
query_results.rewind()
send_emails_dict = {x.get("userId"): x.get("sendEmailNotification") for x in query_results}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM