Advertisement
vikramk3

unique_users.py

Oct 16th, 2014
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Oct 12 17:25:10 2014
  4.  
  5. @author: vikramk3
  6. """
  7.  
  8. #!/usr/bin/env python
  9. """
  10. Use an aggregation query to answer the following question.
  11.  
  12. Provide a list of unique users.
  13.  
  14. Please modify only the 'make_pipeline' function so that it creates and returns an aggregation
  15. pipeline that can be passed to the MongoDB aggregate function. As in our examples in this lesson,
  16. the aggregation pipeline should be a list of one or more dictionary objects.
  17. Please review the lesson examples if you are unsure of the syntax.
  18.  
  19. This code was run locally on my machine.
  20.  
  21. """
  22.  
  23. def get_db(db_name):
  24.     from pymongo import MongoClient
  25.     client = MongoClient('localhost:27017')
  26.     db = client[db_name]
  27.     return db
  28.  
  29. def make_pipeline():
  30.     # complete the aggregation pipeline
  31.     pipeline = [{"$match":{"address.state":"TX"}},{"$group":{"_id":"$created.uid","count":{"$sum":1}}},{"$sort":{"count":-1}}]
  32.     return pipeline
  33.  
  34. def aggregate(db, pipeline):
  35.     result = db.cities.aggregate(pipeline)
  36.     return result
  37.  
  38. if __name__ == '__main__':
  39.     db = get_db('examples')
  40.     pipeline = make_pipeline()
  41.     result = aggregate(db, pipeline)
  42.     #print result
  43.     import pprint
  44.     pprint.pprint(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement