Skip to content
Share
Explore

Using MONGO DB IN PYTHON

Upcoming TEST 1: Mar 11, 2024 Monday 40 Questions: MCQ / 60 MINUTES


Let’s start by installing MONGODB
and


megaphone

PYTHON MONGO Checklist:


Checklist for Creating a Colors Database in MongoDB using Python:

Install MongoDB:

Download and install MongoDB from the official website

*** Choose the Option to install MONGOD as a service.
image.png
Start the MongoDB server by running the command mongod in a terminal or command prompt. ​
image.png
image.png
Using Visual Studio code to get this application going:
START VSC and make a Directory for your work:

Install PyMongo: Ensure that Python is installed on your system.

Install the PyMongo library using pip by running the command
pip install pymongo in a terminal or command prompt.
image.png

Create a Python Script:

Open Visual Studion Code and create a new Python script (e.g., create_colors_database.py).

Connect to MongoDB:

Import the MongoClient class from the pymongo library.

Create a MongoClient instance to connect to the local MongoDB server.
Create a Database:
Add code to create a new MongoDB database using the MongoClient instance.
Verify Database Creation:
//
In order to work with `pymongo`, you must first ensure that you have the `pymongo` library installed. You can install it using the following pip command if it's not already installed:
```bash pip install pymongo ```
Now, let's take a step-by-step look at creating a
MongoClient instance, creating a new database, and verifying its creation in Python.

**1. Create a MongoClient Instance**

First, you need to import `MongoClient` from `pymongo` and create an instance of `MongoClient` that will connect to your local MongoDB server.
Normally, MongoDB runs on port 27017 by default.
Here's how to establish the connection:
from pymongo import MongoClient
# Connect to the local MongoDB server client = MongoClient('localhost', 27017) ```
Alternatively, the connection string can be used:
```python # Connect to the local MongoDB server with connection string client = MongoClient('mongodb://localhost:27017/') ```

2. Create a Database

MongoDB creates databases and collections automatically for you if they do not exist already. Here's how you would create a new database:
```python # Create a new database called 'mydatabase' db = client['mydatabase'] ```
A database in MongoDB is not created until it gets content, so at this point, `mydatabase` is just a Python variable that will be mapped to a MongoDB database once content (like a collection) is added to it.

**3. Verify Database Creation**

Although databases in MongoDB are created lazily, you can still list all databases to verify whether or not your database name is registered as a part of the system.
Below is a simple code snippet to create a collection
and verify that the database has been created.
In MongoDB, a collection is analogous to a table in relational databases:
Assuming 'mydatabase' has no collections, let's create one to initialize the database
db.create_collection('mycollection')
# Now list all the databases in MongoDBdatabase_list = client.list_database_names() print(database_list)
# Check if 'mydatabase' exists in the list of databases if 'mydatabase' in database_list: print("'mydatabase' exists.") else: print("'mydatabase' does not exist or has not been initialized with any data.") ```
In the above code, we tried to create a `collection` to ensure that the database is created.
Then we list all database names and check if our new database is in that list, even though the presence of a database in the list is not a definitive confirmation until at least one document is inserted into a collection.
Remember, a database in MongoDB stands up only upon insertion of the first document into a collection within that database (or, in some cases, when a collection is created explicitly). Thus, until you perform an actual insert operation, the new database may not show up in the server's database list.

In MongoDB, collections are analogous to tables in relational databases and can be created explicitly or implicitly.
When you add a document into a collection that does not exist, MongoDB automatically creates the collection.
Here's how to create a collection both implicitly and explicitly using PyMongo:
**Implicit Collection Creation**
When you insert a document into a collection that hasn't been created yet, MongoDB creates the collection automatically:
```python from pymongo import MongoClient
# Establishing a connection to the MongoDB server client = MongoClient('localhost', 27017)
# Selecting the database - it will be created if it does not exist db = client['mydatabase']
# Inserting a document - the collection 'mycollection' will be created implicitly ​result = db.mycollection.insert_one({'name': 'John', 'age': 30})
# You can now check that the 'mycollection' exists print('Collection created:', 'mycollection' in db.list_collection_names()) ```
**Explicit Collection Creation**
You can explicitly create a collection using the `create_collection` method. This is useful if you want to configure collection options, such as setting capped collections which limit the size or the number of documents a collection can have.
```python from pymongo import MongoClient
# Establishing a connection client = MongoClient('localhost', 27017)
# Selecting the database db = client['mydatabase']
# Explicitly creating a collection named 'mycollection' collection = db.create_collection('mycollection')
# Verifying that 'mycollection' exists print('Collection created:', 'mycollection' in db.list_collection_names()) ```
In the explicit creation, `create_collection` throws an error if the collection already exists unless you set the `strict` option to `False`.
Note that explicitly creating a collection without any options is not very common since MongoDB's philosophy embraces an implicit creation of collections and databases when they are first used.

To write to an existing "planetmars" database without re-creating it, you can follow these steps:

Connect to the MongoDB server and select the "planetmars" database using PyMongo.
from pymongo import MongoClient

# Connect to the local MongoDB server
client = MongoClient('localhost', 27017)

# Select the 'planetmars' database
db = client['planetmars']
Choose the collection within the "planetmars" database where you want to insert the records. If the collection already exists, you can directly insert the documents into it. If the collection does not exist, it will be created implicitly when you insert the first document.
# Choose the collection
collection = db['mycollection']

Insert the documents into the collection using the insert_one() or insert_many() method. The insert_one() method is used to insert a single document, while the insert_many() method is used to insert multiple documents at once.

# Insert a single document
result = collection.insert_one({'name': 'John', 'age': 30})

# Insert multiple documents
documents = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 35}]
result = collection.insert_many(documents)
Check the result of the insertion operation. The insert_one() and insert_many() methods return an instance of the InsertOneResult and InsertManyResult classes, respectively. You can access the inserted document's _id field from the result.
# Print the inserted document's _id
print(result.inserted_id)
By following these steps, you should be able to write to the existing "planetmars" database without re-creating it.It's important to remember that a collection is not physically created until you actually insert some data into it.
So, when you call `create_collection` without defining any options, you're essentially telling MongoDB to prepare to create the collection once a document is inserted unless you specify options that take effect immediately, like capped collections.
>>>>>
To acquire the "my_collection" collection without trying to re-create it, you can modify your code as follows:
from pymongo import MongoClient

# Connect to the local MongoDB server
client = MongoClient('localhost', 27017)

# Select the 'planetmars' database
db = client['planetmars']

# Choose the collection 'my_collection'
collection = db['my_collection']

# Now you can use the 'collection' object to perform operations on the collection
# For example, you can insert a document
result = collection.insert_one({'name': 'John', 'age': 30})

# Print the result
print(result)

# You can also check if the collection exists
if 'my_collection' in db.list_collection_names():
print("'my_collection' exists.")
else:
print("'my_collection' does not exist or has not been initialized with any data.")



By using the db['my_collection'] syntax, you can directly access the "my_collection" collection without trying to re-create it. This way, you can perform operations on the existing collection, such as inserting documents.


Please note that if the collection does not exist, it will be created implicitly when you insert the first document.

>>>>>

Making the Bears Database

Add Collection (Optional):
If desired, include code to create a collection within the created database. Finalize and Test:
Close the MongoClient connection to release resources. Lab Activity:
Instruct students to run the Python script and observe the output to verify the successful creation of the database. Encourage students to modify the script to perform additional interactions with the database, such as inserting sample data or querying the collection. Additional Considerations:
Emphasize error handling and proper resource management in the Python script.
Guide students to organize the code and structure the database interactions for clean and efficient implementation.
By following this checklist, students can ensure a structured approach to creating a MongoDB database with Python, adhering to best practices in software writing and information architecture.

megaphone

Exception handling if collection exists

To handle the situation where the collection already exists, you'll need to catch the `CollectionInvalid` exception that `create_collection` raises when it tries to create a collection that already exists. The `pymongo.errors` module provides this exception class. Amend the script as shown below:
```python from pymongo import MongoClient from pymongo.errors import CollectionInvalid
# Connect to the local MongoDB server client = MongoClient('localhost', 27017)
# Select the database db = client['TheBearCave']
try: # Attempt to create the collection collection = db.create_collection('mycollection') print(f"Collection created: {collection}") except CollectionInvalid: print("Collection 'mycollection' already exists.")
# Since MongoDB lazy-creates databases, you can verify if 'TheBearCave' # database is listed among the ones created after an interaction requiring its creation database_list = client.list_database_names()
print("Database list:", database_list)
# Check if 'TheBearCave' exists in the list of databases if 'TheBearCave' in database_list: print("'TheBearCave' database exists.") else: print("'TheBearCave' database does not exist or has not been initialized with any data.") ```
In this updated version, the script will attempt to create the collection 'mycollection' within 'TheBearCave' database. If the collection already exists, the `CollectionInvalid` exception will be caught, and a message indicating that the collection already exists will be printed instead of the script failing with an exception.
It's important to note that `create_collection` will not only check for the existence of the collection by name but will also verify if the options match. If the collection already exists with different options, it will still raise `CollectionInvalid`. Therefore, use this feature when specific creation options are needed. Otherwise, letting MongoDB create the collection automatically when data is inserted might be more straightforward and error-tolerant.

Python works with MongoDB through drivers like PyMongo, which is the official MongoDB driver for synchronous Python applications.
PyMongo provides an intuitive API for accessing databases, collections, and documents in MongoDB.
It allows for easy manipulation, iteration, and printing of objects retrieved from MongoDB, as they are compatible with dictionaries and lists.
To work with MongoDB in Python, you need to install the PyMongo driver, which can be done using PIP.
Once installed, you can use PyMongo to connect to a MongoDB database, query, retrieve, write, and delete data, as well as run database commands
.
If you encounter any issues when connecting to a MongoDB database locally using Python, ensure that the MongoDB server is running and that you are using the correct connection parameters. The connection string should specify the correct host, port, and database name.
Additionally, make sure that the necessary MongoDB driver, such as PyMongo, is installed in your Python environment
.

Installing MONGODB:
megaphone

When using MongoDB as the persistence layer for a Python MVC 3-tier application, it's recommended to set up a separate MongoDB database for the application. This allows for better isolation, management, and scalability of the application's data.

Setting up a separate MongoDB database provides the following advantages:
Isolation: Each application can have its own dedicated database, preventing interference or data conflicts with other applications sharing the same database.
Scalability: It allows for independent scaling of the database resources based on the specific needs and workload of the application.
Management: Separating databases makes it easier to manage access controls, backups, and maintenance specific to the application.
When teaching students, it's important to:
demonstrate the process of setting up a separate MongoDB database for their application and guide them on best practices for database naming conventions, user permissions, and data organization within the database.
This approach aligns with the principles of information architecture and ensures a structured and organized data storage for their applications.


minus

Lesson Plan: Using MongoDB as the Persistence Layer for Python MVC 3-tier Application

Objective: To teach students how to integrate MongoDB as the persistence layer for a Python MVC 3-tier application.
Prerequisites:
Prior knowledge of Python programming language
Understanding of MVC architecture
Basic knowledge of MongoDB

Lesson Plan:
Introduction to MongoDB:
a. Explanation of MongoDB as a NoSQL database
b. Advantages of using MongoDB in web applications
c. Comparison with traditional SQL databases
Setting up MongoDB:
a. Installation of MongoDB
b. Running MongoDB server locally
c. Basic commands to interact with the MongoDB shell

Introduction to MVC 3-tier architecture:
a. Overview of Model-View-Controller (MVC) pattern
b. Understanding the concept of 3-tier architecture (presentation layer, business logic layer, data access layer)

Integrating MongoDB with Python:
a. Connecting to MongoDB using the PyMongo library
b. Creating a database and collection
c. Performing CRUD operations using PyMongo

Designing the Persistence Layer:
a. Implementing data access objects (DAO) for MongoDB
b. Defining models to represent data in the application
c. Encapsulating MongoDB access within the data access layer

Building the Business Logic Layer: a. Creating Python classes for business logic b. Interacting with the MongoDB data access layer from the business logic layer c. Implementing validation and business rules
Implementing the Presentation Layer:
a. Creating views to display data from the business logic layer
b. Handling user input and invoking business logic
c. Integrating the presentation layer with the business logic layer and MongoDB data access layer
Testing and Debugging: a. Writing test cases for MongoDB interactions b. Debugging common issues related to MongoDB integration c. Ensuring data consistency and integrity in the application
Best Practices and Optimization: a. Discussing best practices for using MongoDB in Python applications b. Optimizing queries and data access for improved performance c. Ensuring security and data privacy considerations
Conclusion and Project Work: a. Recap of key concepts learned b. Assigning a project to students to build a Python MVC 3-tier application with MongoDB as the persistence layer c. Providing resources and guidance for the project work
Assessment:
Multiple-choice or short-answer questions to test theoretical knowledge
Project evaluation based on the implementation of MongoDB integration in the Python MVC 3-tier application
Note: Throughout the lesson, emphasis should be placed on the importance of structuring code and organizing data in a clean and efficient manner, following software writing principles and best practices.

error

Programming MONGO DB with Python: Lab 1


Lab Worksheet: Creating a MongoDB Database with Python
Objective: To create and interact with a MongoDB database using Python and the PyMongo library.
Prerequisites:
Basic knowledge of Python programming Installation of Python and PyMongo library Installation of MongoDB server Instructions:
Setting up MongoDB Server: a. If MongoDB server is not installed, download and install it from the official MongoDB website (https://www.mongodb.com/try/download/community). b. Start the MongoDB server by running the command mongod in a terminal or command prompt.
Installing PyMongo: a. Ensure that Python is installed on your system. b. Install the PyMongo library using pip by running the command pip install pymongo in a terminal or command prompt.
Creating a Python Script: a. Open your preferred text editor or integrated development environment (IDE) to create a new Python script (e.g., create_mongodb.py).
Connecting to MongoDB: a. In the Python script, import the MongoClient class from the pymongo library. b. Create a MongoClient instance to connect to the local MongoDB server:
python
from pymongo import MongoClient
# Create a MongoClient to connect to the local MongoDB server client = MongoClient('localhost', 27017) Creating a Database: a. Add code to create a new MongoDB database using the MongoClient instance:
python
# Access or create a database named 'mydatabase' db = client['mydatabase'] Verifying Database Creation: a. Provide code to print the list of available databases to verify that 'mydatabase' was created:
python
# List the available databases print(client.list_database_names()) Adding Collection (Optional): a. If desired, include code to create a collection within the created database:
python
# Create a new collection named 'mycollection' within the 'mydatabase' database collection = db['mycollection'] Finalizing and Testing: a. Close the MongoDB client connection to release resources:
python
# Close the MongoClient connection client.close()
Lab Activity:
a. Instruct students to run the Python script and observe the output to verify the successful creation of the 'mydatabase' database.
b. Encourage students to modify the script to create additional collections or perform basic CRUD (Create, Read, Update, Delete) operations to further interact with the MongoDB database.
Assessment:
Check the students' scripts to ensure they correctly implemented the steps to create a MongoDB database using Python and PyMongo.
Evaluate students' understanding based on their ability to modify the script for additional database interactions.
Note: Emphasize the importance of
error handling: try/catch
proper resource management: close connections when you are finished using them
and best practices for working with MongoDB and Python.
Additionally, provide guidance on structuring and organizing the code for improved information architecture and software writing.

CRUD
minus

Create RECORDS


To insert multiple records (documents) in a MongoDB collection using PyMongo, you use the `insert_many` method.
Below is an example code snippet to insert 10 records (documents) with details about different species of bears:
```python from pymongo import MongoClient
# Connect to the local MongoDB server client = MongoClient('localhost', 27017)
# Select the database db = client['TheBearCave']
# Define a list of bear records (documents) to be inserted bear_records = [ {"species": "Brown Bear", "habitat": "Forests", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Polar Bear", "habitat": "Arctic", "diet": "Carnivore", "family_life": "Solitary, maternal"}, {"species": "American Black Bear", "habitat": "Forests and mountains", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Asian Black Bear", "habitat": "Forests", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Giant Panda", "habitat": "Bamboo forests", "diet": "Herbivore", "family_life": "Solitary"}, {"species": "Sloth Bear", "habitat": "Grasslands, forests", "diet": "Omnivore", "family_life": "Solitary with cubs"}, {"species": "Spectacled Bear", "habitat": "Andean jungles", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Sun Bear", "habitat": "Tropical forests", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Grizzly Bear", "habitat": "Forests, mountains", "diet": "Omnivore", "family_life": "Solitary"}, {"species": "Andean Bear", "habitat": "Cloud forests", "diet": "Omnivore", "family_life": "Solitary"} ]
# Insert the records (documents) into the collection 'bears' result = db.bears.insert_many(bear_records)
# Output the number of records inserted and their collection IDs print(f"{len(result.inserted_ids)} records were inserted.") print("The inserted IDs are:", result.inserted_ids) ```
This script connects to the MongoDB server, selects the 'TheBearCave' database, creates a list of ten bear records, and inserts them into a collection named 'bears'. After the insertion, it prints out how many records were inserted along with their respective ObjectIDs.
Remember to run the necessary MongoDB service on your local environment before executing the script. The `insert_many` method automatically creates the 'bears' collection if it does not already exist during data insertion.
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.