pymongo | InvalidOperation while trying to return result

Question:

I’ve been trying to make something using MongoDB with the help of pymongo python package but I’ve encountered a error that I can’t solve.
So basically, I used the collection.find() function to assign the returned data to a variable and then tried to return a row using result["role.id"] as you can see in the code below.
Unfortunately, it gives me this error when it tries to return the result:

InvalidOperation: cannot set options after executing query

Code:

def post_exists_and_return_value(collection, id):
result = None
if collection == "muted_role":
    result = muted_role_collection.find({"_id": id})
elif collection == "member_role":
    result = member_role_collection.find({"_id": id})
if len(list(result)) == 1:
    return result["role_id"] # error happens here (debugging mode flagged it)
else:
    return False
Asked By: Asux

||

Answers:

The find() method returns a Cursor instance, per the documentation here. So your current code is attempting to access a field of the first document, but it is doing so against the cursor rather than the first result of the cursor.

Your two options are:

  1. Use find_one() method instead, documented just a little bit earlier on the same page here
  2. Iterate your cursor to operate on the first document in the results held by the cursor.

It seems like the first is perfectly reasonable for what you are attempting to do here.

Answered By: user20042973
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.