[英]Pymongo can't get record with find_one() / find()
I can't get any record from mongodb. 我无法从mongodb获得任何记录。 DB is test and collection is name.
数据库是测试,集合是名称。 With shell mongo i can get this record.
使用shell mongo,我可以获得此记录。 When i am using find() i could only get value '-1'.
当我使用find()时,我只能获得值“ -1”。
My code: 我的代码:
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)
Error: 错误:
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
I find an answer. 我找到答案。 To get access to database collection it should be formatted using dictionary-style access:
要访问数据库集合,应使用字典式访问对其进行格式化:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.