MongoDB + Python CRUD examples
This is for my PDS class
Retrieve records
import pymongo
from pymongo import MongoClient
client = MongoClient()
# Get the sampleDB database
db = client.adventureworks
collection = db.inventory
# Get all items in the collection
for item in collection.find():
print(item)
# Get all items in the collection with cost less than $1.00
for item in collection.find({"cost": {"$lt":1}}):
print(item)
Insert records
### EXAMPLE to show how you insert documents into MongoDB
import pymongo
from pymongo import MongoClient
client = MongoClient()
# Get the sampleDB database
db = client.adventureworks
collection = db.inventory
# Insert three documents
collection.insert_many(
[
{"name": "Protractor", "cost": 0.50, "color": "red"},
{"name": "Pencil case", "cost": 6.50, "type": "zipper", "design" : "Hello Kitty"},
{"name": "Pencil Lead", "cost": 1.50, "thickness": 0.7, "brand" : "Pentel"},
]
)
Update records
### EXAMPLE to show how you update documents from MongoDB
import pymongo
from pymongo import MongoClient
client = MongoClient()
# Get the sampleDB database
db = client.adventureworks
collection = db.inventory
# Get all items in the collection
for item in collection.find():
print(item)
# Update object which is Ruler
collection.update_one({"name": "Ruler"}, # Filter criteria
{"$set": {"weight": 100}} # New value
)
Delete records
### EXAMPLE to show how you delete documents from MongoDB
import pymongo
from pymongo import MongoClient
client = MongoClient()
# Get the sampleDB database
db = client.adventureworks
collection = db.inventory
collection.delete_one({"name": "Protractor"})
Perform aggregate
from pymongo import MongoClient
client = MongoClient()
db = client.adventureworks # client.database_name
collection = db.inventory #db.collection_name
# { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
pipeline = [{ '$group': { "_id": "$category", "count": { '$sum': 1 } } }]
result = collection.aggregate(pipeline);
for r in result:
print(r)
import pymongo
import pandas as pd
from pymongo import MongoClient
client = MongoClient()
db = client.adventureworks
collection = db.inventory
data = pd.DataFrame(list(collection.find()))
print(data)
Convert to Pandas DataFrame
import pymongo
import pandas as pd
from pymongo import MongoClient
client = MongoClient()
db = client.adventureworks
collection = db.inventory
data = pd.DataFrame(list(collection.find()))
print(data)
Comments
Post a Comment