3

我有一个 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'
4

1 回答 1

1

也许您的某些文档没有 twitter 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'])
于 2013-05-22T14:43:50.683 回答