2013-07-15 137 views
9

我連接我的mongodb使用pymongo到:如何判斷一個字段是否存在?

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

我有一個光標和我通過每一個創紀錄的循環:

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 

的原因try/except是因爲如果["entities"]["urls"]不存在,它錯誤了。

我怎麼能確定[ 「實體」] [ 「網址」]是否存在?

+0

也請更正我的術語「字段」 –

回答

7

記錄是一本字典,其中鍵「實體」鏈接到另一個字典,所以只是檢查,看看是否「網址」是那本詞典。

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

如果你只是想在任何情況下進行,你也可以使用get。

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

如果沒有這樣的密鑰,這將導致msgurl等於None。

+0

非常感謝!檢查記錄[「實體」]是否存在? –

+0

你可以做同樣的事情:要麼「如果」實體「在記錄:」或「record.get(」實體「)」。 – llb

+0

非常感謝這麼多。我儘快接受(5分鐘) –

6

只需添加到@martingreber答案,檢查是否字段存在和值不爲空。

mongo_coll.find({ 
$and:[ 
    {"entities.urls": {$exists:1}}, 
    {"entities.urls": {$not: {$type:10}}} 
]}) 
相關問題