Skip to content

Instantly share code, notes, and snippets.

@KiraDynnes
Created October 13, 2017 08:42
Show Gist options
  • Save KiraDynnes/9f5b3dd34845428c3f69560b1d4d9b14 to your computer and use it in GitHub Desktop.
Save KiraDynnes/9f5b3dd34845428c3f69560b1d4d9b14 to your computer and use it in GitHub Desktop.
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.Northwind # Get the database
#get a look at which collections are in the database
collection = db.collection_names(include_system_collections=False)
for collect in collection:
print(collect)
#short name for relevant collections
prod = db['products']
order = db['orders']
ordDet = db['order-details']
#ex 1
relevantOrders = [item['OrderID'] for item in order.find({"CustomerID": "ALFKI"})]
productAndOrderID = [{k: item[k] for k in ("ProductID", "OrderID")} for item in ordDet.find({'OrderID':{'$in':relevantOrders }})] #order details are extrated for relevant orders
#loop over productsIDs, for each product ID, the dictionary is updatet with the product name taken from the product collection
for item in productAndOrderID:
prodName = [a['ProductName'] for a in prod.find({'ProductID': item['ProductID']})][0]
item.update({"productName": prodName})
#print the result
print(*productAndOrderID, sep = "\n")
#ex2
#reuse the detaild order information from ex1 and update with categoryID (completly parallel to ex4.1 where product Name was added)
for item in productAndOrderID:
catId = [a['CategoryID'] for a in prod.find({'ProductID': item['ProductID']})][0]
item.update({"CategoryID": catId})
db.ALFKIsOrders.insert(productAndOrderID) #ceate new collection only holding ALFKIs orders
alsOrders= db['ALFKIsOrders'] #and a short name for the new collections
#extract only orderIds which fullfill the criteria (more than two different categoryIDs within the order)
relevantOrdersDiffType = []
for order in range(0,len(relevantOrders)):
catIds = []
for item in alsOrders.find({"OrderID": relevantOrders[order]}):
catIds.append(item['CategoryID'])
if len(set(catIds)) > 1:
relevantOrdersDiffType.append(item['OrderID'])
#extract only the relevant orders from ALFKIs order collection
result = [{k: item[k] for k in ("ProductID", "productName","OrderID","CategoryID")} for item in alsOrders.find({'OrderID':{'$in':relevantOrdersDiffType}})]
print(*result, sep = "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment