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

354
Views
Query in MongoDB (Pymongo) with operator $in using with ObjectId

I have a list of ID's and I want to query a collection based on that list. The field I'm filtering is id_, it is an ObjectID.

Example:

list = ['abcd','mnop','qrst']

I want to search documents that the _id is in that list:

cursor = db.find( {"_id": { "$in": list} }   )
cursor = db.find( {"_id": { "$in": ObjectId(list)} }   )

I tried both options above and none of them worked. The first one returned empty, and the second one throws a type error: TypeError: id must be an instance of (bytes, str, ObjectId), not <class 'list'>

How can I correct my code?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As @prasad_ said, it is needed to generate the ObjectId from the string.

list_ = ['abcd','mnop','qrst']
list_ = [ObjectId(x) for x in list_]
cursor = db.find( {"_id": { "$in": list_} } )

So the "$in" operator of MongoDB refers to the list that has ObjectId's as its content.

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!