2013-07-15 81 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}}} 
]}) 
相关问题