Python MongoDB
Introduction to MongoDB
MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like document format. Python provides an interface to interact with MongoDB using libraries like pymongo, which allows developers to connect to a MongoDB instance, perform CRUD operations, and manipulate the database.
Environment Setup
To use MongoDB with Python, you need to install the pymongo library:
# Install pymongo using pip
!pip install pymongo
Connecting to MongoDB
Below is an example of how to connect to a MongoDB database and create a new collection.
from pymongo import MongoClient
# Establishing a connection
client = MongoClient('localhost', 27017)
db = client['school_db']
# Creating a collection
students_collection = db['students']
print("Connected to MongoDB and collection created successfully!")
Output
Connected to MongoDB and collection created successfully!
Inserting Data into MongoDB
# Inserting a document into the 'students' collection
student = {
'name': 'John Doe',
'age': 21,
'subjects': ['Math', 'Science']
}
students_collection.insert_one(student)
print("Document inserted successfully!")
Output
Document inserted successfully!
Fetching Data from MongoDB
# Fetching all documents from the collection
for student in students_collection.find():
print(student)
Output
{'_id': ObjectId('...'), 'name': 'John Doe', 'age': 21, 'subjects': ['Math', 'Science']}
Explanation
- MongoClient: Used to connect to the MongoDB server.
- Database and Collection: Similar to databases and tables in SQL.
- Document: The basic unit of data in MongoDB, equivalent to a row in SQL.