Search code examples
pythonmongodbpymongo

Pythonic way to check if field in Mongodb Document exists on a conditional


All the answers that I've read shows to use the following code to find out if the field exists in the collection. :

db.inventory.find( { qty: { $exists: true, $ne: false } } )

I was looking for something that conditionally checks in the current document being checked has that certain field/key. Ofcourse I tried doing something like:

doc['properties.color'] is None:
     print("Property does not exists")

But my documents have made it harder. Not all my document has that property within a field therefore causing an error:

KeyError: u'properties.color'

That is why I needed the conditional statement while I loop at every document. I hope someone can help.

Thanks.


Solution

  • The general opinion is that the pythonic way is to ask for forgiveness instead of permission.

    Assuming the code snippet you posted is in a context like this:

    if doc['properties.color'] is None:
        print("Property does not exists")
    else:
        # do something with doc['properties.color'], e.g.:
        color = doc['properties.color']
    

    If you ask for forgiveness instead of permission, you work with the error you are facing instead of against it:

    try:
        # do something with doc['properties.color'], e.g.:
        color = doc['properties.color']
    except KeyError:
        # this would be your `if`-branch from above
        # handle this case:
        print("Property does not exist")