Aditya Kalia
Aditya Kalia

Reputation: 21

How do you query a pymongo db with a list of object_ids?

I'm trying to query a MongoDB but for a list of _ids.

For example:

db.test.find(ObjectId(['4ecc05e55dd98a436ddcc47c',4ecc05e55dd98a436adfc47c', ....] ))

Upvotes: 1

Views: 1097

Answers (2)

Aditya Kalia
Aditya Kalia

Reputation: 21

Declare your list:

list_of_ids = [ObjectId("4ecc05e55dd98a436ddcc47c"),ObjectId("4ecc05e55dd98a436adfc47c")]

and run db.test.find({'_id': {'$in': list(list_of_ids)}}.

Upvotes: 1

Belly Buster
Belly Buster

Reputation: 8814

You need to use the $in operator, e.g.

db.test.find({'_id': {'$in': [ObjectId("4ecc05e55dd98a436ddcc47c"), ObjectId("4ecc05e55dd98a436adfc47c")]}})

This works in both Mongo shell and pymongo.

Upvotes: 2

Related Questions