Reiion
Reiion

Reputation: 943

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.

Upvotes: 0

Views: 2769

Answers (2)

Anoroah
Anoroah

Reputation: 2109

Using pymongo you can check just like you check on a dictionary. For example:

document = collection.find_one({"author_id": author_id})
if "author_username" in document:
    print("Author has a username)

Upvotes: 0

Pit
Pit

Reputation: 4046

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

Upvotes: 1

Related Questions