Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

812
Views
Python mongodb/motor "'ObjectId' object is not iterable" error while trying to find item in collection

I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:

from bson import ObjectId


async def get_single_template(db, template_id):
    template = await db.templates.find_one({ '_id': ObjectId(template_id) })
    return template

And I'm getting an error:

ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

"template_id" is a valid string, like "601401887ecf2f6153bbaaad". ObjectId created from it - too. It fails only to work inside find_one() method. When I'm using find() with that id it works well. I've tried from bson.objectid import ObjectId too - no difference. I'm using motor library to access mongo. Is there something that I'm missing?

P.S. Links to the corresponding docs:

https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-by-objectid

Though I'm using motor async library, I can't find direct examples in it's docs. Basically, it wraps pymongo. I can only find examples in other's source code.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Well, I've found out what caused that issue. The problem was not in the way I've tried to query data, but in the way I've tried to return it. I've forgotten to convert ObjectId to string in the entity that I've retrieved from database and tried to return it 'as is'. My bad.

over 4 years ago · Santiago Trujillo Report

0

I encountered this problem as well while using Python motor for Mongodb. In your app.collection.find_one(...), add {'_id': 0} along with the dictionary which has the value you want to search for.

So it should be like this:

await app.collection.find_one({"value": val},{'_id': 0})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!