简体   繁体   English

Python - 无法将 Python 连接到 MongoDB

[英]Python - Cannot connect Python to MongoDB

I'm using Python 3.4 the latest version of MongoDB and already installed pymongo using我正在使用 Python 3.4 最新版本的 MongoDB 并且已经安装了 pymongo 使用

pip install pymongo

When I run this.py file当我运行 this.py 文件时

from pymongo import MongoClient

if __name__ == "__main__":
    con = MongoClient()

    db = con.test_database

    people = db.people

    people.insert({'name':'Mike', 'food':'cheese'})
    people.insert({'name':'John', 'food':'ham', 'location':'UK'})
    people.insert({'name':'Michelle', 'food':'cheese'})

    peeps = people.find()

    print("INSERT & FIND TEST")
    for person in peeps:
        print(person)

I got this error:我收到此错误:

Traceback (most recent call last):
  File "C:/Users/Alberto/Documents/Python/Kivy/Code/testmongo.py", line 10,     in <module>
people.insert({'name':'Mike', 'food':'cheese'})
  File "C:\Python34\lib\site-packages\pymongo\collection.py", line 2197, in insert
with self._socket_for_writes() as sock_info:
  File "C:\Python34\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
  File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 712, in _get_socket
server = self._get_topology().select_server(selector)
  File "C:\Python34\lib\site-packages\pymongo\topology.py", line 142, in select_server
address))
  File "C:\Python34\lib\site-packages\pymongo\topology.py", line 118, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it

Anyone know how to fix this?有人知道怎么修这个东西吗?

if you are using Local Mongodb如果您使用本地 Mongodb

myclient = pymongo.MongoClient('mongodb://<yourUsername>:<yourPassword>@<IPAddress>:27017/<yourDB>?retryWrites=true&w=majority')

If you are using Atlas Mongodb如果您使用的是 Atlas Mongodb

myclient = pymongo.MongoClient('mongodb+srv://<yourUsername>:<yourPassword>@<YourCluster>.mongodb.net/<yourDB>?retryWrites=true&w=majority')

Just try to replace the connection with the following line. 只需尝试用以下行替换连接。

con = MongoClient('localhost', 27017)

It works fine for me. 这对我来说可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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