I have a following mongodb:
some records looks like {'_id': ObjectId('62790ce20375a639af1d8676'), 'visit_id': 594817704, 'transaction' : 10}
some has only this form: {'_id': ObjectId('62790ce20375a639af1d8679'), 'visit_id': 594817704}
Using this code I can search for all collections that consists of transaction_id:
collection.find({'transaction_id': { "$exists":True }
But if I would like to get a record with specific transaction_id, this code does not work (it tooks infinite time to search):
collection.find({'transaction_id': 10})
I tried to combine both approaches, that is to firstly ask if transaction_id exists and then search for transaction_id = 10, but it did not work:
collection.find({'transaction_id': { "$exists":True }, 'transaction_id': 10})
How can I fix it, please?
2
Answers
should work.
No need for
$exists
if you want a specific value.See how it works on the playground example
How big is your data set? do you have an index on
transaction_id
?If your query is slow, consider add an hashed index on
transaction_id
.Without the index, the DB should check all documents to see if any of them has
transaction_id: 1000
. This isO(n)
operations wheren
is the number of your documents. The index stores this information, so it will be one check onlyO(1)
.In order to create the index use the UI or, using the shell:
Where you replace
<collectionName>
with your collection name.Please refer my code.
To create index