how to determine whether a field exists?

18,161

Solution 1

Record is a dictionary in which the key "entities" links to another dictionary, so just check to see if "urls" is in that dictionary.

if "urls" in record["entities"]:

If you just want to proceed in any case, you can also use get.

msgurl = record["entities"].get("urls")

This will cause msgurl to equal None if there is no such key.

Solution 2

I'm not familiar with pymongo, but why don't you change your query so it only returns results that contain "urls"? Something like:

mongo_coll.find({"entities.urls": {$exists:1}}) 

http://docs.mongodb.org/manual/reference/operator/exists/

Share:
18,161

Related videos on Youtube

Alex Gordon
Author by

Alex Gordon

Check out my YouTube channel with videos on Azure development.

Updated on September 15, 2022

Comments

  • Alex Gordon
    Alex Gordon over 1 year

    I'm connecting to my mongodb using pymongo:

    client = MongoClient()
    mongo = MongoClient('localhost', 27017)
    mongo_db = mongo['test']
    mongo_coll = mongo_db['test']   #Tweets database
    

    I have a cursor and am looping through every record:

    cursor = mongo_coll.find() 
    for record in cursor:    #for all the tweets in the database
        try:
          msgurl = record["entities"]["urls"]    #look for URLs in the tweets
        except:
          continue
    

    The reason for the try/except is because if ["entities"]["urls"] does not exist, it errors out.

    How can I determine whether ["entities"]["urls"] exists?

  • Alex Gordon
    Alex Gordon almost 11 years
    thanks so much! what about checking whether record["entities"] exists?
  • llb
    llb almost 11 years
    You can do the same thing: either if "entities" in record: or record.get("entities").
  • Alex Gordon
    Alex Gordon almost 11 years
    awesome thanks so much. ill accept as soon as i'm able (5 min)