Python MongoClient Examples
Introduction to MongoClient
The class MongoClient enables you to make successful MongoDB server connections with your code. The MongoClient can accomplish this with client instances. When you use the PyMongo driver with the MongoClient, coding and connections happen more quickly. As a result, it becomes easier to make API calls to access your MongoDB databases and retrieve or change the data. Learn more with this tutorial that explains how to use the MongoClient with the MongoDB PyMongo driver. There are also several Python MongoClient examples for you to try.
If you’re already familiar with how to use the PyMongo driver with MongoDB and would like to skip the detailed steps, go to Just the Code.
Prerequisites
To prepare for your Python MongoClient examples, download and install Python3, the PIP Python Package Installer, the Community Edition of MongoDB, and PyMongo as indicated in the sections below.
Install Python 3
Download and install the latest release of Python.
Check the installation with the command
python3 -V
at the command prompt. You can also do this at the terminal.
NOTE: Get more details such as the path where Python was installed as well as the environment by inputting the command
which python3
.
Install the PIP Python Package Installer
You might already have a pre-installation of PIP. To determine if you have PIP, type either
pip -V
orwhere pip3
.Install PIP in Linux by using the repository of the distro like this:
1 | install python3-pip |
Install the Community Edition of MongoDB
Select the correct version of MongoDB for your OS.
Install MongoDB on macOS
- For macOS, use Homebrew to complete the installation:
1 | brew install mongodb-community@4.2 |
Install MongoDB on Windows
Download and install the MongoDB Community Server.
Verify the connection and the version with the command
mongod
.
Installing PyMongo
The PIP package installer is what you should use to install PyMongo on your OS.
- Use the command
pip3 install
to get the Python 3pymongo
library:
1 | pip3 install pymongo |
- Alternatively, use the command
python3
to activate the programming language on your OS:
1 | python3 -m pip install pymongo |
- Now, within your console or script, do a
pymongo
importation. If you experience anImportError
, try to reinstall PyMongo.
To proceed with getting prepared for completing your Python MongoClient examples, get Python to return the string of the library’s version after it import’s PyMongo.
- In
idle3
(IDLE), a Python’s interactive environment, copy and paste the code below:
1 | import pymongo; pymongo.version |
NOTE: Ensure that PyMongo is compatible. Check that your version of MongoDB is v2.6 or higher by going to the command line and inputting
mongod --version
.
Connect with MongoClient()
- To make a MongoDB default connection, access
python3
(Python console) or use an instance. Either way, use this code:
1 2 | import pymongo pymongo.MongoClient() |
- After that, you should see a response similar to this:
1 2 3 4 5 6 | MongoClient( host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True ) |
Here’s the explanation of the code you just entered:
The
host
default string parameter is based on the port27017
, so it’slocalhost:27017
.When the
type()
function receives the method callMongoClient()
that you pass to it, the result should look something like this:
1 2 | type( pymongo.MongoClient() ) <class 'pymongo.mongo_client.MongoClient'> |
As shown above, a PyMongo MongoClient instance is returned by the method call.
Python MongoClient example connection
- Try this connection example that passes environmental variables of MongoDB.
NOTE: It’s assumed that you have on a server, PyMongo. The server has a dedicated IP and some variables (environmental).
1 2 3 4 5 6 7 8 | from pymongo import MongoClient client = MongoClient( host = '987.65.4.3:27017', # <-- IP and port go here serverSelectionTimeoutMS = 3000, # 3 second timeout username="objectrocket", password="1234", ) |
The code you just entered above has a 3-second timeout, which means if it doesn’t connect within that time, it stops trying to connect.
A
MongoClient()
libraryclient
instance should be returned if the connection was successful.
Python MongoClient Examples
See a method and class attribute list by passing the class MongoClient
to the dir()
Python function. You’ll see server_info()
and list_database_names()
information returned in the list.
Get MongoDB server information from MongoClient
- The server MongoDB has data to show when you use a client instance in this manner:
1 2 | server_info = client.server_info() print (server_info) |
- A dictionary object that is JSON-compliant is returned after you invoke the client’s method call
server_info()
:
1 | print ("\nserver info keys:", server_info.keys()) |
- Here’s an example of the type of list that will be printed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | server info keys: dict_keys( [ 'version', 'gitVersion', 'modules', 'allocator', 'javascriptEngine', 'sysInfo', 'versionArray', 'openssl', 'buildEnvironment', 'bits', 'debug', 'maxBsonObjectSize', 'storageEngines', 'ok' ] ) |
- Find out the MongoDB server version with this code:
1 | print ("\nserver version:", server_info["version"]) |
Get the database names from a MongoClient instance
- Use the code below to view every database name that is on the Mongo server:
1 2 | database_names = client.list_database_names() print ("\ndatabases:", database_names) |
NOTE: The current MongoClient method is
list_database_names()
. It replaceddatabase_names()
which is outdated.
Get a document using a MongoClient() instance
- An instance can be used to obtain documents from
MongoClient()
as long as you gain entry into the database name and its collection by treating them as client instance attributes.
Access a MongoDB database and collection
- Treat the database and its collection like a dictionary key to access them:
1 | db = client["some_db"] |
- Here’s how to use an instance of that database to get the collection:
1 | col = db["some_col"] |
- You can also use objects attributes to get the database and its collection like this:
1 2 | db = client.some_db col = db.some_col |
Find a document stored in the MongoDB collection
- Locate and print a single document with the
col
(collection instance) command:
1 2 | doc = col.find_one() print ("\nfind_one() result:", doc) |
The code you just entered above utilized the method call in JavaScript command findOne()
.
- The result should resemble a print out like this:
1 2 3 4 5 | find_one() result: {'_id': ObjectId('5def3dd8cad060b8ef9cc2fa'), 'foo key': 'bar value', 'int key': 42.0 } |
Run the Python MongoClient examples script
Next, save the code you entered above as a script in Python. Name it
mongoclient_examples.py
.Use the command
python3
to run the script:
1 | python3 mongoclient_examples.py |
- The result should look like this:
1 2 3 4 5 6 7 8 9 | ... server info keys: dict_keys(['version', 'gitVersion', 'modules', 'allocator', 'javascriptEngine', 'sysInfo', 'versionArray', 'openssl', 'buildEnvironment', 'bits', 'debug', 'maxBsonObjectSize', 'storageEngines', 'ok']) server version: 4.2.1 databases: ['admin', 'config', 'local', 'some_db'] find_one() result: {'_id': ObjectId('5def3dd8cad060b8ef9cc2fa'), 'foo key': 'bar value', 'int key': 42.0} |
Conclusion
The MongoClient()
class for the PyMongo driver library for MongoDB creates client instances. Its main function is to enable you to connect to the MongoDB database efficiently and effortlessly. Whether you’re changing data or retrieving it, every connection matters. This tutorial showed you how to use MongoClient and gave you some Python MongoClient examples for the MongoClient driver library PyMongo. Feel free to connect fluidly today.
Just the Code
Here’s the code for the entire sample script used in this tutorial featuring Python MongoClient examples.
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 | #!/usr/bin/env python3 #-*- coding: utf-8 -*- # import the MongoClient class from pymongo import MongoClient # host variables for MongoDB DOMAIN = 'localhost' PORT = 27017 # create an instance of MongoClient() client = MongoClient( host = DOMAIN + ":" + str(PORT), serverSelectionTimeoutMS = 3000, # 3 second timeout username = "objectrocket", password = "1234" ) # get the server information server_info = client.server_info() print (server_info) print ("\nserver info keys:", server_info.keys()) # get the MongoDB server version string print ("\nserver version:", server_info["version"]) # get the database_names from the MongoClient() database_names = client.list_database_names() print ("\ndatabases:", database_names) # create database & collection instances db = client.some_db col = db.some_col # find one document stored on the collection doc = col.find_one() print ("\nfind_one() result:", doc) |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started