Check If A MongoDB Server Is Running Using The PyMongo Python Driver

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When you work on a MongoDB database project, it’s important to verify that your port and domain are correct. Having the wrong settings and not realizing it right away can quickly lead to slowed productivity and increased frustration. This tutorial shows you how to check MongoDB server running PyMongo Python so that an exception is raised if the server doesn’t connect. You benefit by being able to correct the settings and make method API calls without further hesitation.

If you know the steps and want to forgo the details of this tutorial, skip to Just the Code.

Prerequisites

  • Install the MongoDB database application.

  • Install PyMongo, the Python driver for MongoDB. It’s recommended to use PIP3 to install PyMongo like this:

1
pip3 install pymongo

Use MongoDB Compass Graphical User Interface (GUI) to try to make a server connection

  • Make an effort to connect with the server by way of the MongoDB Compass GUI if you have the application. You’ll indicate the domain name and port you’re trying to connect.

Screenshot of MongoDB Compass not able to connect to a custom port

  • If it fails, you’ll see a message similar to this:
1
MongoDB is not running on the provided host and port

Why MongoDB doesn’t raise exceptions naturally

MongoDB is a powerful document database that focuses on search and document retrieval capabilities. Exception raising is not the highest priority. But that should be okay giving what MongoDB has to offer far outweighs how it handles exceptions.

When the MongoClient() receives the settings of the port and domain and they aren’t the same as the server, an exception won’t automatically be raised. The good news is that there are ways to go around it so your coding isn’t hindered in the least.

Screenshot of the PyMongo driver returning a client instance of a MongoDB client in Python IDLE

Raise an exception with the server_info() client object method

  • The server_info() method of the client object can be called when MongoDB returns a client instance. You’re verifying that the instance is genuine.
1
2
3
client = MongoClient(host = ["localhost:1111"])

client.server_info()
  • An exception ServerSelectionTimeoutError is shown when the port string and domain are settings are wrong.

Use the parameter serverSelectionTimeoutMS for the connection call timeout

  • The method of the MongoClient() for the timeout you’ll set is called serverSelectionTimeoutMS. In milliseconds is the integer value because it portrays the API call timeout setting.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pymongo import MongoClient

import time

# epoch time before API call

start = time.time()

try:

# attempt to create a client instance of PyMongo driver

client = MongoClient(host = ["localhost:1111"], serverSelectionTimeoutMS = 2000)

# call the server_info() to verify that client instance is valid

client.server_info() # will throw an exception

except:

print ("connection error")

# print the time that has elapsed

print (time.time() - start)

The above code stops the API call to connect to MongoDB after a few seconds time has elapsed, and raises an exception.

Screenshot of Python IDLE throwing a ServerSelectionTimeoutError exception when the server_info method gets called

>NOTE: Thirty seconds is the default timeout if you don’t set the timeout integer of the serverSelectionTimeoutMS method.

Do an importation of the PyMongo driver Python packages

  • Server connection errors are caught when you import the method MongoClient and the pymongo.errors library.
1
2
3
# import the MongoClient class libraries

from pymongo import MongoClient, errors

Make a Python function declaration to use PyMongo to connect

  • A MongoClient client instance will be returned when you use the function def to try to make a MongoDB server connection.
1
def mongodb_connect(domain, port):

Make one string to concatenate the parameters of the port and the domain

1
2
3
# create a domain and port string for the MongoDB server

domain_str = str(domain) + ":" + str(port)

Use the host string to make a MongoClient() client instance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try:

# print the port and domain to connect to

print ("nTrying to connect to MongoDB server:", domain, "on port:", port)

# connect to a MongoDB server that doesn't exist

client = MongoClient(

host = [domain_str],

# timeout is in milliseconds

serverSelectionTimeoutMS = 2000

)

Determine if connection settings are valid

  • Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError. Use the indentation try-except.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# server_info() should raise exception if host settings are invalid

print ("server_info():", client.server_info())

except errors.ServerSelectionTimeoutError as err:

# catch pymongo.errors.ServerSelectionTimeoutError

print ("pymongo ERROR:", err)

# set the client instance to None in case of connection error

client = None

return client
  • If the connection fails, the former object of the client instance will convert into an object NoneType.

Run a test by passing a few settings so that an AttributeError is raised

  • Make the connection fail on purpose to test the ability for the function to discern a failed connection.

>NOTE: For raising exceptions, the object NoneType doesn’t have the same attributes of MongoDB as the AttributeError does. This is why the AttributeError is recommended.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# call the mongodb_connect() function

client = mongodb_connect("localhost", 1111)

print ("client:", client)

# use a try-except block when getting database/collection

try:

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

except AttributeError as error:

# should raise AttributeError if mongodb_connect() function returned "None"

print ("Get MongoDB database and collection ERROR:", error)

Analyze the client instance of PyMongo

  • Verify the connection by using the statement if to analyze if there is a None client instance to check MongoDB server running PyMongo Python.
1
2
3
4
5
6
7
8
9
10
11
12
13
# or evaluate the client object instead

if client != None:

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

else:

print ("Client instance is invalid")

Perform some API calls to find exceptions of the ServerSelectionTimeoutError

  • As an alternate to the method server_info(), locate the errors with a indentation block try-except.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# connect to a MongoDB server that doesn't exist

client = MongoClient(

host = ["DOES_NOT_EXIST"],

# timeout is in milliseconds

serverSelectionTimeoutMS = 2000

)

print ("nCreating database and collection form 'bad' client instance")

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

Use the method find_one() to locate exceptions of the ServerSelectionTimeoutError to check MongoDB server running PyMongo Python

1
2
3
4
5
6
7
8
9
10
11
# try to make a find_one() method call to the collection

try:

one_doc= col.find_one()

print ("nfind_one():", one_doc)

except errors.ServerSelectionTimeoutError as err:

print ("nfind_one() ERROR:", err)

Conclusion

This tutorial explained various ways to check MongoDB server running PyMongo Python. In it, you learned how to intentionally raise exceptions to verify that a connection failed. You also discovered how to confirm a valid MongoDB server connection.

In a successful connection, the correct port settings and domain were specified. It’s good to know that you can verify your connection settings in a variety of ways. Now you can pick which method works best for you and have some backup techniques to select from as well.

Just the Code

Here’s a complete sample code to for you to check MongoDB server running Pymongo Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3

#-*- coding: utf-8 -*-

# import the MongoClient class

from pymongo import MongoClient, errors

import time

# create a timestamp before making API call

start = time.time()

# check the seconds that have elapsed

try:

client = MongoClient(host = ["localhost:1111"], serverSelectionTimeoutMS = 2000)

client.server_info() # will throw an exception

except:

print ("connection error")

# print the time difference

print (time.time() - start)

# define a function that validates the client instance

def mongodb_connect(domain, port):

# create a domain and port string for the MongoDB server

domain_str = str(domain) + ":" + str(port)

try:

# print the port and domain to connect to

print ("nTrying to connect to MongoDB server:", domain, "on port:", port)

# connect to a MongoDB server that doesn't exist

client = MongoClient(

host = [domain_str],

# timeout is in milliseconds

serverSelectionTimeoutMS = 2000

)

# server_info() should raise exception if host settings are invalid

print ("server_info():", client.server_info())

except errors.ServerSelectionTimeoutError as err:

# catch pymongo.errors.ServerSelectionTimeoutError

print ("pymongo ERROR:", err)

# set the client instance to None in case of connection error

client = None

return client

# call the mongodb_connect() function

client = mongodb_connect("localhost", 1111)

print ("client:", client)

# use a try-except block when getting database/collection

try:

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

except AttributeError as error:

# should raise AttributeError if mongodb_connect() function returned "None"

print ("Get MongoDB database and collection ERROR:", error)

# or evaluate the client object instead

if client != None:

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

else:

print ("Client instance is invalid")

# connect to a MongoDB server that doesn't exist

client = MongoClient(

host = ["DOES_NOT_EXIST"],

# timeout is in milliseconds

serverSelectionTimeoutMS = 2000

)

print ("nCreating database and collection form 'bad' client instance")

# create new database and collection instances

db = client.SomeDatabase

col = db["Some Collection"]

# try to make a find_one() method call to the collection

try:

one_doc= col.find_one()

print ("nfind_one():", one_doc)

except errors.ServerSelectionTimeoutError as err:

print ("nfind_one() ERROR:", err)

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.