与 MongoDB 的连接错误:对象没有属性 'getitem'

Connection error to MongoDB: object has no attribute 'getitem'

尝试连接到 MongoDB 时,我遇到错误

我该如何解决这个问题?

Traceback (most recent call last): File "D:/MongoDB-U/Python/Codes/Try.py", line 17, in print (item['name']) TypeError: 'NoneType' object has no attribute 'getitem'

代码:

import pymongo

from pymongo import MongoClient

connection = MongoClient('localhost',27017)

db = connection.test
names = db.things
item  = things.find_one()

print (item['name'])

您正在创建一个 names 集合变量,但随后在 find_one 调用中使用了一个 things 集合变量。应该是:

db = connection.test
things = db.things
item  = things.find_one()

print (item['name'])