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
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.