Guest User

Untitled

a guest
Oct 21st, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. from pymongo import MongoClient
  2. # pprint library is used to make the output look more pretty
  3. from pprint import pprint
  4.  
  5. mongodb_url = "mongodb://localhost:27017"
  6.  
  7. # connect to MongoDB
  8. client = MongoClient(mongodb_url)
  9. db=client.Northwind
  10. # Issue the serverStatus command and print the results
  11. serverStatusResult=db.command("serverStatus")
  12. #pprint(serverStatusResult)
  13.  
  14. top_ten_most_orders = db['order-details'].aggregate([
  15.  
  16. {
  17. # lookup is used to outer join the order_details with the orders table
  18. "$lookup":
  19. {
  20. "from": "orders",
  21. "localField": "OrderID",
  22. "foreignField": "OrderID",
  23. "as": "orders_info"
  24. }
  25. },
  26. # Group records together by OrderId
  27. # and when grouping increment a orderID counter by one for each record that is combined
  28. # and calculate a cumulative sum for each record that is combined, save the result as "Total_Quantity"
  29. { "$group" : {"_id":"$orders_info.CustomerID", "OrderID_counter":{"$sum":1}, "Total_Quantity": {"$sum":"$Quantity"}}},
  30. # sort the result in descending order by orderID_counter
  31. { "$sort": { "OrderID_counter": -1} },
  32. # Finally limit the number of documents to 10
  33. { "$limit": 10 }
  34. ])
  35.  
  36. # Print the result in a nice way
  37. print "Results for exercise 4.3 (Make your own) MongoDB"
  38. print
  39. print "{CustomerID: <12} {TotalOrders: <14} {TotalQty: <14}".format(
  40. CustomerID = "Customer Id",TotalOrders = "Total orders", TotalQty = "Total quantity")
  41. print "------------------------------------------"
  42. for order in top_ten_most_orders:
  43. print "{CustomerID: <12} {TotalOrders: <14} {TotalQty: <14}".format(
  44. CustomerID = order["_id"][0], TotalOrders = order["OrderID_counter"], TotalQty = order["Total_Quantity"])
  45.  
  46. print
  47. print "Total number of lines: {}".format(len(data))
Add Comment
Please, Sign In to add comment