简体   繁体   中英

Key Error in accessing collections from MongoDB (PyMongo)

Why does this work:

import pymongo
from selenium import webdriver
import smtplib
import sys
import json

from pymongo import MongoClient
client = MongoClient('localhost', 27017)

db = client.properties
collection = db['capitalpacific']

fromDB = []

if collection.count() != 0:
    for post in collection.find():
        fromDB.append(post)

print(fromDB[0]['url']) 

correctly prints url only from document 1 of collection (xxx.com)

but I get a keyError when I do this:

for i in range(0, 2):
print(fromDB[i]['url'}

KeyError: 'url'

The documents stored in the DB look like so : {'url':'xxx.com', 'location':'oregon'}

KeyError generally means the key doesn't exist in the dictionary collection.

For example :

>>> mydoc1=dict(url='xxx.com', location='oregon')
>>> mydoc2=dict(wrongkey='yyy.com', location='oregon')
>>> mylist=[]
>>> mylist.append(mydoc1)
>>> mylist.append(mydoc2)
>>> print mylist[0]['url']
xxx.com

>>> for i in range(0, 2):
...     print(mylist[i]['url'])
...
xxx.com
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'url'
>>>

Here, mydoc2 doesn't have a key called 'url', hence the "KeyError" is being raised for the second element in the list.

So,are you sure 'url' exist in first two records. can you print the contents of "fromDB" and make sure that first two records has 'url' key.

>>> print mylist
[{'url': 'xxx.com', 'location': 'oregon'}, {'wrongkey': 'yyy.com', 'location': 'oregon'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM