繁体   English   中英

Pymongo无法使用find_one()/ find()获取记录

[英]Pymongo can't get record with find_one() / find()

我无法从mongodb获得任何记录。 数据库是测试,集合是名称。 使用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

我找到答案。 要访问数据库集合,应使用字典式访问对其进行格式化:

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.

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