【问题标题】:Connection error to MongoDB: object has no attribute 'getitem'与 MongoDB 的连接错误:对象没有属性“getitem”
【发布时间】:2015-01-09 07:11:14
【问题描述】:

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

我该如何解决这个问题?

Traceback(最近一次调用最后一次): 文件“D:/MongoDB-U/Python/Codes/Try.py”,第 17 行,在 打印(项目['名称']) TypeError:“NoneType”对象没有属性“getitem

代码:

import pymongo

from pymongo import MongoClient

connection = MongoClient('localhost',27017)

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

print (item['name'])

【问题讨论】:

  • item 是None,相当于python 中的null。您对 mongo 的查询可能没有返回任何结果。
  • 我在 Mongo 中有一个集合名称
  • import pymongo from pymongo import MongoClient connection = MongoClient('localhost',27017) db = connection.test names = db.things item = things.find_one() print (item['name'])
  • 这并没有改变find_one 正在返回None 的事实。那个收藏有什么吗?
  • 是的,该集合有一个条目 {name : "Will"}

标签: python mongodb pymongo


【解决方案1】:

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

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

print (item['name'])

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2021-05-03
    • 2020-07-02
    • 1970-01-01
    • 2015-01-29
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多