Python and MongoDB

Topics Covered

Overview

A wide range of libraries is provided by Python for MongoDB Python interaction. Some of them are PyMongo, MongoEngine, etc. Python is a very outstanding language for working with MongoDB because of its flexibility, simplicity features, and a wide variety of tools and libraries provided by it.

What is Python?

Python is a very popular object-oriented programming language that is also used for Python MongoDB interaction. MongoDB is a NoSQL database, and it allows the storage of very large data in an unstructured manner, and nowadays, it is becoming a preferred choice as a database for working with modern applications that require high flexibility and scalability. A wide range of libraries is provided by Python MongoDB interaction. One of them and the most commonly used library of Python is PyMongo. It is a Python implementation of the MongoDB API. PyMongo allows us to make a connection with the MongoDB database and allows us to perform the CRUD(Create, Read, Update, Delete) operations and execute queries.
MongoEngine is another library of Python that can be used for working with Python MongoDB. Higher-level abstraction is provided by MongoEngine over the PyMongo, and it also simplifies the operations to be performed on the database, and it simplifies the model-defining process.
Python is a very outstanding language for working with Python MongoDB because of its flexibility, simplicity features, and a wide variety of tools and libraries provided by it.

Prerequisites

First of all, it is required to download and install Python on your system. And to check whether Python is installed in your system or not, type python –version on the command prompt terminal.

Python and MongoDB Atlas Connection

There is a set of packages in PyMongo for the Python MongoDB interaction. Now start with creating and activating a virtual environment.

Now, you can install PyMongo as if you are in a virtual environment. Type the following code in your terminal.

Now, in your code, PyMongo can be used as the Python MongoDB library by import statement.

Creating a Database in MongoDB using Python

Creating a cluster is the first step for the connection establishment of Python MongoDB Atlas.
For writing the code of PyMongo, a file with the name pymongo_get_database.py is required to be created in any folder. Any simple text editor can also be used, such as Visual Studio Code.

Mongodb client can be created by writing the code given below:

A connection string to your database is required for creating a MongoClient. You have to replace the user. pass by your password and cluster in the CONNECTION_STRING. The database is not created by Python MongoDB until you have not inserted collections and documents inside it. So, firstly let us look at how a collection can be created.

Creating a Collection in MongoDB using Python

The collection name is to be passed to the database for creating a collection. In a new file having the name pymongo_test_insert.py, write the code given below:

A collection with the name Students inside the database Students is created by it.

Documents Insertion in MongoDB using Python

For inserting many documents at once, use the pymongo insert_many() method.

For inserting a single document, the insert_one() method can be used.

Now open the command line and move to the folder in which you have saved the file named Pymongo_test_insert.py. And then, run the command given below to execute the file.

Find Documents using Querying in MongoDB using Python

find() is used to view all the documents of the collection. We will create a separate file with the name pymongo_test_query.py for executing the queries.

Now open the command line and move to the folder in which you have saved the file named pymongo_test_query.py. And then, run the command given below to execute the file.

It will print a dictionary object list as an output.

Create an Index on a collection in MongoDB using Python

Indexes help in optimizing the performance of searches performed on the database. createindex() method is used for creating the index, and indexes can be created by providing a custom name. Below is a query for creating an index on the Students collection on the name.

The db.collection.getIndexes() method is used for viewing all the indexes' names. The index can not be renamed once it is created. We can drop that particular index and recreate an index with the same name.

PyMongo: Using Python with MongoDB

One of the most commonly used libraries of Python for working with MongoDB is PyMongo. It is a Python implementation of the MongoDB API. PyMongo allows us to make the connection with the MongoDB database and allows us to perform the CRUD(Create, Read, Update, Delete) operations and execute queries.

Installation

To use PyMongo, first of all, you need to install PyMongo in your Python MongoDB environment. The fastest method of installing PyMongo is installing it with pip, as PyMongo is available on PyPI.

Run the following command on your terminal:

After executing this command, PyMongo is installed successfully in your Python environment.

Connection Establishment

MongoClient instance creation is required for establishing a connection with the database. The client is provided by the class for the MongoDB server or instance. First of all import MongoClient from PyMongo. Create the object of the client for communicating with your currently running instance of MongoDB

The code given above establishes the connection with the default port(27017) and host(localhost). But you can also set a custom port, host, and other connection parameters using the set of arguments taken by the MongoClient.

Below is an example of creating a connection with a custom port and host:

MongoDB URI format can also be used.

After the MongoClient instantiation, its instance can be used for referring to the particular database connection.

Database, Collections and Documents

After connecting instances, any database managed by the server specified can be accessed. Dot notation can be used for defining which database you desire to use.

In the code given above, students_list is the name of the database. The database is created by MongoDB if it does not exist, but it can create a database at the time the first operation is performed on the database. Inserting data in data with the help of PyMongo is very much similar to what you did in the Mongo shell. Firstly you need to create a document using Python MongoDB dictionaries.

After creating a document, you need to mention which collection you want to use. For that, dot notation can be used with the object of the database.

.insert_one() method is used for inserting one document at a time.

We can insert multiple documents simultaneously by .insert_many() method.

.find() is used for fetching all the documents from the collection.

MongoEngine: using Python with MongoDB

PyMongo is considered a powerful and great driver of Python MongoDB interaction, but for many projects, PyMongo is a bit too low-level. It is required to write a very large amount of code for performing delete, update, retrieve, and insert documents operation consistently.
Higher-level abstraction is provided by MongoEngine over the PyMongo, and it also simplifies the operations to be performed on the database, and it simplifies the model-defining process. MongoEngine is a type of object-document mapper(ODM), and it is similar to SQL-based object-relational mapper (ORM). Class-based abstraction is provided by the MongoEngine, so all the created models are class.

Installation

The pip command is used for installing MongoEngine as it is available on PyPI.

After installation, the next step is to create a connection with your recent running instance of MongoDB Python.

Connection Establishment

mongoengine.connect() is used for establishing a connection with your database. Several arguments are taken by this function.

Write the code given below:

Here, first of all, we are setting the name of the database db to “myDatabase”. It is the database name in which you desire to work. Then host and port are provided for connecting the current instance of MongoDB. These two parameters can be omitted as you're using the default port. Then you simply need to type connect("students_list").

Database, Collections and Documents

For document creation with MongoEngine, first of all, it is required to define what type of data you desire to have for the documents. This means you have to define the document Schema. Base or model classes are provided by the MongoEngine for defining document Schema. In ORMs, class is similar to tables, and instances are similar to the table rows. But in MongoEngine, the class is similar to the collection, and instances of it are similar to documents.
For model creation, a Document is required to be subclassed, and required fields are provided as the class attributes.

In this model, you are telling the MongoEngine that you expect a document with the name Student, and it has .name and .address.
The .save() method is required to be called on the document object for saving the document in the database. If the database document already exists, then all the modifications are applied to the existing document. And if a document does not exist, then a new document will be created.
Below is a code for creating and saving a student into the Student database:

Every subclass of the document class has a .objects attribute that can be used for fetching the documents of the particular collection. For instance, here is the code for printing the .name of all the students.

FAQs

Q:- How can MongoDB be connected using Python?

A:- For connecting MongoDB using Python, you can use the library provided by it, such as PyMongo, and MongoEngine.

Q:- How can data be inserted in MongoDB collection?

A:- You can use collection.insert_one() and collection.insert_many() for inserting documents in the MongoDB collection. insert_one() is used to insert a single document. And multiple documents can be inserted simultaneously using insert_many().

Conclusion

  • Wide range of libraries are provided by Python for making Python MongoDB interaction easier. Some of them are PyMongo, MongoEngine, etc.
  • Creating a cluster is the first step for connecting Python MongoDB Atlas.
  • PyMango is a Python implementation of the MongoDB API, which allows making the connection between Python MongoDB database and allows performing the CRUD(Create, Read, Update, Delete) operations and executing queries.
  • Higher-level abstraction is provided by MongoEngine over the PyMongo, and it also simplifies the operations to be performed on the database, and it simplifies the model-defining process.