简体   繁体   中英

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

I can't get any record from mongodb. DB is test and collection is name. With shell mongo i can get this record. When i am using find() i could only get value '-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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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