- Deployed MongoDB 4.4.3
- Python 3.9.1
pip install pymongo==3.11.3
import os
from pprint import pprint
from pymongo import MongoClient
Initialize the connection
MONGODB_USERNAME = os.environ.get("MONGODB_USERNAME")
MONGODB_PASSWORD = os.environ.get("MONGODB_PASSWORD")
MONGODB_HOST = os.environ.get("MONGODB_HOST")
MONGODB_DATABASE = os.environ.get("MONGODB_DATABASE")
MONGODB_COLLECTION = os.environ.get("MONGODB_COLLECTION")
uri = f"mongodb://{MONGODB_USERNAME}:{MONGODB_PASSWORD}@{MONGODB_HOST}"
connection = MongoClient(uri)
db = connection[MONGODB_DATABASE]
collection = db[MONGODB_COLLECTION]
doc = {
"item": "canvas",
"qty": 100,
"tags": ["cotton"],
"size": {
"h": 28,
"w": 35.5,
"uom": "cm"
}
}
docs = [
{
"item": "journal",
"qty": 25,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A"
},
{
"item": "notebook",
"qty": 50,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "A"
},
{
"item": "paper",
"qty": 100,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "D"
},
{
"item": "planner",
"qty": 75,
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"status": "D"
},
{
"item": "postcard",
"qty": 45,
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"status": "A"
}
]
Select All Documents in a Collection
Specify Equality Condition
Specify Conditions Using Query Operators
query = {"status": {"$in": ["A", "D"]}}
query = {"status": "A", "qty": {"$lt": 30}}
query = {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]}
Specify AND as well as OR Conditions
query = {
"status": "A",
"$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]
}
Set the value of a field to current date
update_operator = {
"$currentDate": {
"current_date_default": True,
"current_date": {"$type": "date"},
"current_timestamp": {"$type": "timestamp"}
}
}
Increment the value of the field by the specified amount
update_operator = {
"$inc": {
"emptyField": 1,
"a.a": 1,
}
}
pipeline.append({
"$limit": 100,
})
pipeline.append({
"$match": {"status": "A"}
})
pipeline.append({
"$project": {"status": 1}
})
pipeline.append({
"$sort": {"status": -1}
})
collection.insert_one(doc)
Insert multiple documents
collection.insert_many(docs)
Number of documents in the collection
collection.count_documents(query)
cursor = collection.find(query)
collection.update_one(query, update_operator)
collection.update_many(query, update_operator)
collection.replace_one(query, doc)
collection.delete_one(query)
collection.delete_many(query)
cursor = collection.aggregate(pipeline, allowDiskUse=True)
for doc in cursor:
pprint(doc)
FROM python:3.9.1-buster
RUN pip install pymongo==3.11.3
docker build -t python-pymongo-usage .
MONGODB_USERNAME=user
MONGODB_PASSWORD=topsecret
MONGODB_HOST=mongodb
MONGODB_DATABASE=newdb
MONGODB_COLLECTION=testcollection
docker run --rm --link mongodb --env-file .env -it python-pymongo-usage python
- https://docs.mongodb.com/manual/crud/