我有一个mongodb收集朋友,我运行代码
for doc in friends.find():
print doc
我明白了:
{u'_id': ObjectId('519ccdb86383cf1444445a1c'), u'twitter_id': 609034617}
{u'_id': ObjectId('519ccdb86383cf1444445a1d'), u'twitter_id': 253090547}
{u'_id': ObjectId('519ccdb86383cf1444445a1e'), u'twitter_id': 146221326}
{u'_id': ObjectId('519ccdb86383cf1444445a1f'), u'twitter_id': 1267350151}
{u'_id': ObjectId('519ccdb86383cf1444445a20'), u'twitter_id': 8806112}
{u'_id': ObjectId('519ccdb86383cf1444445a21'), u'twitter_id': 82589355}
但如果我这样做:
for doc in friends.find():
print doc['twitter_id']
我收到错误:
Traceback (most recent call last):
File "C:\Users\schatterjee\workspace\scorefollowback.py\application.py", line 65, in <module>
print doc['twitter_id']
KeyError: 'twitter_id'
答案 0 :(得分:1)
也许您的某些文档没有推特ID。以下是具有良好数据的示例shell会话:
>>> import pymongo
>>> conn = pymongo.MongoClient('localhost', 27017)
>>> users = conn['test']['users']
>>> users.remove()
>>> users.insert({'twitter_id': '11111111'})
>>> users.insert({'twitter_id': '22222222'})
>>> for user in users.find():
... print(user['twitter_id'])
...
11111111
22222222
您可能想尝试使用$exists
来确保字段存在,如下所示:Syntax: { field: { $exists: <boolean> } }
for friend in friends.find({ twitter_id: { $exists: true } }):
print(friend['twitter_id'])