Search code examples
pythonmongodbpymongo

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?


Solution

  • 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");