Skip to content

MongoDB pymongo Python Package AQSA Spark By {Examples}

  • by

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.

1. Install pymongo in Python

Install the pymongo package, before you can use 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.

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 which by default is 27017. Once you have the details, connect to the MongoDB from python by using pymongo.MongoClient().

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

Here, we have given Python code that 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.

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 is provided where we have created 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.

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. Take the code example shown below to include the documents in the collection.

#Insert the Document 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. Hence, the code has printed the following inserted document IDs to the console.

5. Create an Index from the Collection using Pymongo

Moreover, we can create an index from the documents by importing the Pymongo. The create_index() method is used to create the index in Pymongo as given below.

#Create an Index from the Collection
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.

6. Query Collection using Pymongo

At last, we queried the collection using Pymongo. We use the find() method to query for the specified documents in a MongoDB collection. The following is the code query for the document that meets the condition.

#Query 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 a Cursor object. The for loop is used to iterate over the Cursor and print each document to the console as displayed.

7. Conclusion

In conclusion, we have discussed the usage of the Pymongo module by connecting with a MongoDB server and performing basic operations. Pymongo is widely used in Python to build scalable and flexible applications.

More details about this topic can be found here.

 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. 1. Install pymongo in Python  Read More MongoDB 

Leave a Reply

Your email address will not be published. Required fields are marked *