Python - 无法将Python连接到MongoDB

时间:2016-02-16 04:38:26

标签: python mongodb pymongo

我正在使用Python 3.4最新版本的MongoDB,并已使用

安装了pymongo
pip install pymongo

当我运行此.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)

我收到了这个错误:

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

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试使用以下行替换连接。

con = MongoClient('localhost', 27017)

它适用于我。