0

I tried to connect to mongodb using pymongo using:

Code:

from pymongo import MongoClient
Client = MongoClient()
db = Client["Libraby"]
collection = db["book"]
book = {}
book["title"] = "XYZ"
book["name"] = "abc"
book["published"] = 2014
collection.insert(book)

And I got the error as:

Traceback (most recent call last):
  File "`<pyshell#8>`", line 1, in `<module>`
`collection.insert(book)`
  File `"C:\Python34\lib\site-packages\pymongo\collection.py"`, line 2935, in `insert`
    check_keys, manipulate, write_concern)
  File `"C:\Python34\lib\site-packages\pymongo\collection.py"`, line 598, in `_insert`
    bypass_doc_val, session)
  File `"C:\Python34\lib\site-packages\pymongo\collection.py"`, line 578, in `_insert_one`
    True, _insert_command, session)
  File `"C:\Python34\lib\site-packages\pymongo\mongo_client.py"`, line 1098, in `_retryable_write`
`with self._tmp_session(session) as s:`
  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 1404, in `_tmp_session`
    s = self._ensure_session(session)
  File `"C:\Python34\lib\site-packages\pymongo\mongo_client.py"`, line 1391, in `_ensure_session`
    return self.start_session(causal_consistency=False)
  File `"C:\Python34\lib\site-packages\pymongo\mongo_client.py"`, line 1369, in `start_session`
    server_session = self._get_server_session()
  File `"C:\Python34\lib\site-packages\pymongo\mongo_client.py"`, line 1377, in `_get_server_session`
    return self._topology.get_server_session()
  File `"C:\Python34\lib\site-packages\pymongo\topology.py"`, line 416, in `get_server_session
    None)`
  File `"C:\Python34\lib\site-packages\pymongo\topology.py"`, line 199, in `_select_servers_loop`
    self._error_message(selector))
**pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it**
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99
  • if `nc -vz localhost 27017` gives you the same thing then your mongodb server is not running on your machine. – Ghilas BELHADJ Jan 19 '18 at 12:55
  • Look at [this section](https://docs.mongodb.com/tutorials/install-mongodb-on-windows/#step-2-start-mongodb-) here – Ghilas BELHADJ Jan 19 '18 at 13:01
  • You may want to fix this snippet `db = Client["Libraby"]`. This could be the source of the issue if your table is named `Library` in mongo, but otherwise it will cause issues elsewhere when `Library` is correctly spelled. Also, when I recently set up Mongo I had a difficult time at first but I found mongo's Compass quite useful for visualizing what was actually happening in my `Table`. This will also help you follow through the steps as you get started. – Brandon Barney Jan 19 '18 at 13:10
  • @GhilasBELHADJ Thank you, I am new to python :D –  Jan 19 '18 at 13:47

0 Answers0