2016-06-01 68 views
0

我的文檔結構是這樣的....如何使用python在mongodb中迭代遊標?

enter image description here

我跑這個查詢

test_run_names = self._database.suiteruns.find({'user': user_id, {'$or': [{'name': {'$exists': True}},{'name': {'$eq': ""}}]}}) 

test_run_names是遊標類型。

如何迭代它並獲得我需要的屬性?

我做了什麼?

for t in test_run_names 
    print (t['name']) #throws a key error 
+0

我建議看看https://api.mongodb.com/python/current/tutorial.html – Saleem

回答

1

也許你有沒有名的元素。

試試這個:

for t in test_run_names 
    print (t.get('name')) 
+0

好吧,我想出來的,但isnt t ['name']與t.get('name')相同? – cafebabe1991

+0

如果名字不存在並且t.get('name')將會返回一個錯誤,如果沒有名字變量,那麼t.get('name')將返回none –

+0

我的意思是,如果名字沒有定義,它會拋出一個錯誤 –