• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB pymongo Python Package

In order to interact with MongoDB from Python use the pymongo package. A pymongo Python package offers an easy but effective interface to interact with MongoDB. In this article, we will explore the usage of pymongo to connect to a MongoDB server and perform some basic operations on a collection.

Advertisements

1. Install pymongo in Python

Install the pymongo package before using it in Python to interact with the MongoDB database or collection. Using the pip package is the simplest way to accomplish this. We can simply run the following command in the command-line interface which will install the latest version of PyMongo and its dependencies.


# Install pymongo in Python
python -m pip install pymongo

The pymongo is successfully installed here as can be seen below.

pymongo mongodb python

Now, we can verify the pymongo module installation by importing the module in the Python command line like below.


# Verify the Pymongo module
import pymongo

The module pymongo is successfully executed which indicates that we can use pymongo in Python to connect to MongoDB and perform CURD operations. 

2. Python Connect to MongoDB using pymongo

To connect to a MongoDB server using Pymongo, we need to know the address of our MongoDB server and port number. Once you have the details, connect to MongoDB from Python by using pymongo.MongoClient(). By default, the port would be 27017 unless you changed it to another.


# Connecting MongoDB server
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
print(client.list_collection_names())

Here, the Python code connects to the MongoDB server through the use of the MongoClient class. The connection string is specified to the MongoClient().  We then list the available databases on the server using the list_database_names() method. The following listed databases are all displayed in the output.

pymongo mongodb python

3. Create MongoDB Collection using PyMongo

As the MongoDB connection has been established in the above section. Now, we can easily perform the MongoDB operation with the Python environment.  The following code creates a new database called NewDatabase and a new collection called student. Then, the print statement simply indicates that the collection was created successfully.


# Create MongoDB Collection
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['NewDatabase']
col = db['student']
print("Collection created sucessfully")

The output shows that the database and collection within the database have been created. Note that the above code does not insert any data into the student collection, it simply creates the collection.

use of Pymongo

A complete tutorial on MongoDB can be found here.

4. Insert the Document into the Collection using Pymongo

Here, we are going to insert the documents using pymongo into the collection student that is created above. Pymongo has the method insert_many() to insert multiple documents at once. Here is an example.


# Insert documentd into the collection
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
db = client.get_database('NewDatabase')
col = db.get_collection('student')  
docs = [{'name': 'David', 'age': 20},
        {'name': 'Alice', 'age': 25},
        {'name': 'Tyler', 'age': 23}]
result = col.insert_many(docs)
print(result.inserted_ids)

The above code inserts three documents into the student collection using the insert_many() method, which returns an InsertManyResult object containing the inserted document IDs. The code also displays the inserted document IDs to the console.

5. Create an Index from the Collection using Pymongo

To create an index on the collection, use the create_index() method. Indexes improve the performance of the query when the query includes the fields that are part of the index.


# Create an index
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
db = client.get_database('NewDatabase')
col = db.get_collection('student')
col.create_index("name")

Above, the create_index() method creates a single-field index on the name field, which means that queries that filter on the name field will be faster. Thus, we have the following output that shows the index field of the collection student.

pymongo mongodb python

6. Query Collection using Pymongo

We can query the collection using Pymongo find() method, by using this we can query for the specified documents in a MongoDB collection. The following is the code query for the document that meets the condition.


#Q uery Collection
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
db = client.get_database('NewDatabase')
col = db.get_collection('student')
MyQuery = {'age': {'$gt': 20}}
docs = col.find(MyQuery)
for doc in docs:
    print(doc)

Here, the query is constructed using a dictionary with a $gt operator. Then, we conduct a search using the find() method, which yields an Cursor object. The for loop is used to iterate over the cursor and print each document to the console.

pymongo mongodb python

7. Conclusion

In conclusion, we have discussed the usage of the pymongo module which is used to connect to MongoDB from Python language. Pymongo is widely used in Python to build scalable and flexible applications.

More details about this topic can be found here.