In [95]:
import pymongo
from pymongo import MongoClient
import datetime
import re
from pymongo import InsertOne, DeleteOne, ReplaceOne
import datetime
client = MongoClient()
client = MongoClient('mongodb://localhost:27017/')
db = client.homework2
users = db.users
movies = db.movies
In [19]:
movieList = movies.find({"_id": 1})
for movie in movieList:
print movie
In [28]:
occupations = sorted(users.distinct(u'occupation'))
for occupation in occupations:
print occupation
In [107]:
# We will choose 'technician/engineer' and hide movie reviews - limit to first 10 results
engineers = users.find({u'occupation': 'technician/engineer'},
{u'movies':0}).limit(10)
for engineer in engineers:
print engineer
In [108]:
men = users.find({u'gender': 'M'}).count()
print "There are " + str(men) + " men in the database."
In [82]:
regex = re.compile("^5.*")
by_zipcodes = users.find({u'zipcode': regex},
{u'_id':1, u'zipcode': 1}).limit(10)
for zipcode in by_zipcodes:
print zipcode
In [83]:
comedies_from_1998 = movies.find({u'year': 1998, u'category': u'Comedy'}).limit(10)
for comedy in comedies_from_1998:
print comedy
In [104]:
movies_between_1990_and_1995 = movies.find({u'year': {'$gte': 1990, '$lte': 1995}}).count()
print 'There are ' + str(movies_between_1990_and_1995) + ' movies between 1990 and 1995'
In [93]:
movies_before_1992 = movies.find({u'year': {'$lt': 1992}})\
.limit(10)\
.sort('year', pymongo.ASCENDING)
for movie in movies_before_1992:
print movie
I have seen ways to grab the max ID and increment it by one, but this is not safe in general, so I am not implementing it here.
In [113]:
# users.delete_one({u'zipcode': u'68102'})
Out[113]:
In [110]:
me = users.find_one({u'zipcode': u'68102'})
if me is not None:
print me
else:
max_id = users.find_one({u'zipcode': u'68102'})
myself = {u'gender': u'M',
u'age': u'25-34',
u'zipcode': u'68102',
u'occupation': u'technician/engineer'}
result = db.users.insert_one(myself)
my_id = result.inserted_id
print 'created my profile with id ' + str(my_id)
In [111]:
movie_review = {u'moveID': 3272, # Bad Lieutenant
u'rating': 5,
u'timestamp': datetime.datetime.utcnow()}
users.update_one(
{ u'zipcode': u'68102'},
{ "$addToSet":{"movies": movie_review} },
upsert=True)
me = users.find_one({u'zipcode': u'68102'})
print me
In [112]:
regex = re.compile("^681.*")
by_zipcodes = users.find({u'zipcode': regex},
{u'_id':1, u'zipcode': 1}).limit(10)
for zipcode in by_zipcodes:
print zipcode