简体   繁体   中英

How to find_one in mongodb if the key is not always present?

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?

collection.findOne({transaction_id: 10})

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 is O(n) operations where n is the number of your documents. The index stores this information, so it will be one check only O(1) .

In order to create the index use the UI or, using the shell:

db.getCollection(<collectionName>).createIndex( {transaction_id: "hashed" })

Where you replace <collectionName> with your collection name.

Please refer my code.

from pymongo import MongoClient

client = MongoClient('localhost', 27017);

#connect to the DB named testdb
mydatabase = client.testdb

#pickup collection named transactions 
collection = mydatabase.transactions

#find one by transaction_id
res = collection.find_one({transaction_id:10})

#display data
print(res)

To create index

collection.create_index("transaction_id");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM