⬅ Previous Topic
Defining Custom Validation Rules in MongoDBNext Topic ⮕
MongoDB with Node.js using Mongoose⬅ Previous Topic
Defining Custom Validation Rules in MongoDBNext Topic ⮕
MongoDB with Node.js using MongoosePyMongo is the official Python library for interacting with MongoDB. It allows Python developers to easily connect, read, write, and manipulate data in MongoDB using familiar Python syntax.
First, make sure Python is installed. Then, install PyMongo using pip:
pip install pymongo
Let’s start by connecting to a local MongoDB instance.
from pymongo import MongoClient
# Connect to the local MongoDB server
client = MongoClient("mongodb://localhost:27017/")
# Create or access a database
db = client["school"]
# Create or access a collection
students = db["students"]
Explanation: We create a connection using MongoClient
, then access a database and a collection. If they don't exist, MongoDB will create them on the fly when we insert data.
# Insert one document
students.insert_one({
"name": "Alice",
"age": 22,
"subjects": ["Math", "Science"]
})
# Insert multiple documents
students.insert_many([
{"name": "Bob", "age": 24},
{"name": "Charlie", "age": 21, "subjects": ["History"]}
])
Inserted IDs: [ObjectId(...), ObjectId(...)]
Explanation: insert_one()
adds a single document, while insert_many()
can insert multiple documents at once. You don’t need to define a schema beforehand.
To read documents from the collection:
# Find one student
student = students.find_one({"name": "Alice"})
print(student)
# Find all students older than 21
for student in students.find({"age": {"$gt": 21}}):
print(student)
{'_id': ObjectId('...'), 'name': 'Alice', 'age': 22, 'subjects': ['Math', 'Science']} {'_id': ObjectId('...'), 'name': 'Bob', 'age': 24}
Q: Why do we use $gt
instead of Python's >
?
A: MongoDB uses its own set of operators like $gt
(greater than), $lt
(less than), etc., which PyMongo maps directly to its queries.
You can update documents using update_one()
or update_many()
.
# Update one document
students.update_one(
{"name": "Bob"},
{"$set": {"age": 25}}
)
# Update many documents
students.update_many(
{"age": {"$gt": 21}},
{"$inc": {"age": 1}} # Increment age by 1
)
Modified count: 1 Modified count: 2
Explanation: The $set
operator sets a new value, while $inc
increases the current value. These MongoDB operators work the same way in Python with PyMongo.
# Delete one student
students.delete_one({"name": "Charlie"})
# Delete all students younger than 23
students.delete_many({"age": {"$lt": 23}})
Deleted count: 1 Deleted count: 2
Q: What happens if the filter doesn't match any document?
A: Nothing breaks. The operation runs safely and the deleted count will be 0.
client.close()
Best Practice: Always close the connection when done to free resources.
MongoClient
insert_one()
, find()
, update_many()
, and delete_one()
$gt
, $set
, and $inc
are used in PyMongo as they areIn the next lesson, we’ll explore how to use MongoDB with Node.js using Mongoose — a popular ODM library.
⬅ Previous Topic
Defining Custom Validation Rules in MongoDBNext Topic ⮕
MongoDB with Node.js using MongooseYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.