我无法从mongodb获得任何记录。 DB是测试,集合是名称。有了shell mongo我可以得到这个记录。当我使用find()时,我只能获得价值' -1'。
我的代码:
import bottle
import pymongo
# this is the handler for the default path of the web server
@bottle.route('/')
def index():
# connect to mongoDB
client = pymongo.MongoClient('localhost', 27017)
# attach to test database
db = client.test
# get handle for names collection
collection = db.name
# find a single document
my_name = collection.find_one()
return my_name
bottle.run(host='localhost', port=8082)
错误:
Bottle v0.12.13 server starting up (using WSGIRefServer())...
Listening on http://localhost:8082/
Hit Ctrl-C to quit.
Traceback (most recent call last):
File "/home/piotr/python_venv/mongo_M101/lib/python3.6/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/home/piotr/python_venv/mongo_M101/lib/python3.6/site-packages/bottle.py", line 1740, in wrapper
rv = callback(*a, **ka)
File "/home/piotr/PycharmProjects/M101/hello.py", line 17, in index
my_name = collection.find_one()
AttributeError: 'str' object has no attribute 'find_one'
127.0.0.1 - - [25/Feb/2018 13:00:27] "GET / HTTP/1.1" 500 741
答案 0 :(得分:1)
我找到了答案。要访问数据库集合,应使用字典样式访问进行格式化:
client = pymongo.MongoClient('localhost', 27017)
# attach to test database
db = client.test
collection = db[name] #instead db.name
# find a single document
my_name = collection.find_one()