WindowsMacSoftwareSettingsSecurityProductivityLinuxAndroidPerformanceConfigurationApple All

How to Connect MongoDB with a Python Application on Linux

Edited 1 day ago by ExtremeHow Editorial Team

ConnectionMongoDBPythonApplicationLinuxDatabaseDevelopmentIntegrationSetupProgramming

How to Connect MongoDB with a Python Application on Linux

This content is available in 7 different language

MongoDB is a popular NoSQL database that allows developers to easily store and retrieve data. It is known for its flexibility, scalability, and high performance. If you are developing Python applications on a Linux system, you may need to connect your application to a MongoDB database. This guide will give you step-by-step instructions to accomplish this task.

Understanding the environment

Before proceeding, make sure you have the following installed and configured on your Linux machine:

Step 1: Installing PyMongo

The first step is to install the PyMongo library. This library contains tools for working with MongoDB from Python. To install PyMongo, open the terminal and execute:

pip3 install pymongo

Alternatively, you can use:

pip install pymongo

Import PyMongo into the Python shell to make sure your installation is successful and there are no errors.

python3 -c "import pymongo"

If there are no errors, PyMongo is installed successfully.

Step 2: Initializing MongoDB

Make sure MongoDB is running on your local machine. If you installed MongoDB using your package manager, it may already be running as a service. Use the command below to check and start it if needed:

sudo systemctl status mongod

If it is not running, start it as follows:

sudo systemctl start mongod

This command will start the database server, making it ready to accept connections.

Step 3: Setting up the MongoDB database and collections

Before connecting, create at least one database and one collection. You can achieve this in the MongoDB shell or directly through a Python script.

Using the MongoDB shell

Access your MongoDB shell:

mongo

Now, create a new database named “mydatabase”:

use mydatabase

Create a collection named “mycollection”:

db.createCollection("mycollection")

Your database and collection are ready for data entry.

Step 4: Writing a Python script to connect to MongoDB

Now, let's write a Python script to connect to the MongoDB server and perform basic operations.

Connecting to MongoDB

First, let's connect to our MongoDB server using PyMongo:

import pymongo
# Establish a connection to the MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Access the database
db = client["mydatabase"]
# Access the collection
collection = db["mycollection"]

This code connects to MongoDB running on your localhost on the default port 27017. It accesses a database named “mydatabase” and a collection named “mycollection”.

Inserting a document

To insert a document into your collection, use insert_one method:

# Define a document to insert
my_document = {
    "name": "John Doe",
    "age": 29,
    "city": "New York"
}
# Insert the document into the collection
collection.insert_one(my_document)

This will insert a single document with the fields name, age and city.

Retrieving documents

To retrieve documents from a collection, use the find method:

# Retrieve all documents from the collection
for doc in collection.find():
    print(doc)

This script will print all the documents in “mycollection”. You can also use queries to retrieve specific documents:

# Query for documents where name is John Doe
query = { "name": "John Doe" }
# Retrieve and print documents matching the query
for doc in collection.find(query):
    print(doc)

Updating a document

To update documents, use update_one or update_many methods. Here's an example:

# Define the query to select documents
query = { "name": "John Doe" }
# Define the new values
new_values = { "$set": { "age": 30 } }
# Update the document(s)
collection.update_one(query, new_values)

This example updates the age to 30 for documents where the name is John Doe.

Deleting a document

To delete documents from a collection, use delete_one or delete_many methods:

# Define the query for documents to be deleted
query = { "name": "John Doe" }
# Delete the document(s) matching the query
collection.delete_one(query)

This destroys even a single document containing the name John Doe.

Conclusion

You have now learned how to connect a Python application to a MongoDB database running on a Linux system using the PyMongo library. MongoDB's flexibility makes it great for applications requiring scalable and efficient data storage. With PyMongo, interacting with MongoDB from Python is straightforward and intuitive. We've covered installing the necessary software, creating a simple database and collection, and performing basic CRUD operations in Python. You can build on this foundation to create more complex and feature-rich applications that meet your data needs.

If you find anything wrong with the article content, you can


Comments