Alexis Métaireau
Alexis Métaireau

Reputation: 11215

How to query mongodb using a list of items

Given the fact that I have a list of urls (stored in the variable urls), is it possible to make a mongodb query to get all the documents in a collection that have a key (say url) matching with one of those in urls?

I can currently do that by doing N queries to the collection (with N = len(urls)) but I'm pretty sure I'm missing a mongodb feature that allows me to do things quicker.

I must precise I've got this list of urls thanks to a mongodb query.

Here is my code (in python), the two collections are views and resources:

urls = []                                              
for url in db.views.find().distinct("url"):
    urls.append(db.resources.one({'url': url}))

Is there a way I can make those N queries in only one?

EDIT: The final source code to do something like that is using the $in operator, like this:

urls = db.views.find().distinct("url")
list(db.resources.find({'url': {'$in': urls }}))

Upvotes: 3

Views: 4782

Answers (1)

Simon Whitaker
Simon Whitaker

Reputation: 20566

Have a look at the $in operator

Upvotes: 5

Related Questions