1

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?

2
  • 1
    Have you tried something like this for a list of ObjectIds: [ ObjectId('61bde475a216f8027c1379d1'), ...] Commented Dec 22, 2021 at 13:16
  • It Works. list = [ObjectId(x) for x in list]. Thanks. Feel free to awnser the question Commented Dec 22, 2021 at 13:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.