reference
MongoDB with PyMongo Guide
Quick guide to connecting and working with MongoDB using Python's PyMongo library.
Published: November 8, 2024
MongoDB with PyMongo
Installation
pip install pymongo
Connection
Basic Connection
from pymongo import MongoClient
# Connection string format
client = MongoClient('mongodb://<username>:<password>@<ip>:<port>/<database>?authSource=<database>')
# Get database
db = client['db_name']
# List collections
db.collection_names()
Connection String Components
| Component | Description |
|---|---|
username | MongoDB username |
password | User password |
ip | Server IP or hostname |
port | MongoDB port (default: 27017) |
database | Target database name |
authSource | Authentication database |
Basic Operations
Insert
# Insert one
db.collection.insert_one({"name": "John", "age": 30})
# Insert many
db.collection.insert_many([
{"name": "Jane", "age": 25},
{"name": "Bob", "age": 35}
])
Find
# Find one
doc = db.collection.find_one({"name": "John"})
# Find all
for doc in db.collection.find():
print(doc)
# Find with filter
docs = db.collection.find({"age": {"$gt": 25}})
Update
# Update one
db.collection.update_one(
{"name": "John"},
{"$set": {"age": 31}}
)
# Update many
db.collection.update_many(
{"age": {"$lt": 30}},
{"$set": {"status": "young"}}
)
Delete
# Delete one
db.collection.delete_one({"name": "John"})
# Delete many
db.collection.delete_many({"age": {"$lt": 25}})
Quick Reference
| Operation | Method |
|---|---|
| Insert one | insert_one(doc) |
| Insert many | insert_many([docs]) |
| Find one | find_one(filter) |
| Find all | find(filter) |
| Update one | update_one(filter, update) |
| Update many | update_many(filter, update) |
| Delete one | delete_one(filter) |
| Delete many | delete_many(filter) |
| Count | count_documents(filter) |
Tags
mongodbpythonpymongodatabasenosql