Reputation: 345
I had a list of dictionaries that had one field called unique_field_id
and I wanted to get each document for each item of this list.
One way was to do it with a for loop and calling find_one()
query like this:
my_list = [{'unique_field_id': 1}, {'unique_field_id': 2}, {'unique_field_id': 3}]
document_list = list()
for el in my_list:
document = db.collection_name.find_one(el)
document_list.append(document)
The other way and the better and faster way was to do it like this:
my_list = [{'unique_field_id': 1}, {'unique_field_id': 2}, {'unique_field_id': 3}]
my_list_values = [d['unique_field_id'] for d in my_list]
document_list = db.collection_name.find({'unique_field_id': {'$in': my_list_values}})
This was working fine with me until unique field of my documents changed to two fields.
Now I have a list of dictionaries with two fields unique_field_id
and other_unique_field_id
which are indexed together as the unique field of my document.
If I want to take the first approach it would be like this:
my_list = [{'unique_field_id': 1, 'other_unique_field_id': 'a'}, {'unique_field_id': 2, 'other_unique_field_id': 'b'}, {'unique_field_id': 3, 'other_unique_field_id': 'c'}]
document_list = list()
for el in my_list:
document = db.collection_name.find_one(el)
document_list.append(document)
BUT I need to do it the second way and check the $in
statement for index of two fields instead of doing it one by one because it is much faster.
How Can I Do It?
Also I think that there is useful answer in this question which I don't understand fully.
Mongo $in with compound index
Upvotes: 0
Views: 165
Reputation: 3349
Use the $or
operator to find the command.
my_list = [
{'unique_field_id': 1, 'other_unique_field_id': 'a'},
{'unique_field_id': 2, 'other_unique_field_id': 'b'},
{'unique_field_id': 3, 'other_unique_field_id': 'c'}
]
document_list = list(db.collection_name.find({
"$or": my_list
}))
Upvotes: 1