Skip to content

Instantly share code, notes, and snippets.

@codepainkiller
Last active March 18, 2017 00:37
Show Gist options
  • Save codepainkiller/ceb538a8a8aa099a1fdd04f6b1d751f4 to your computer and use it in GitHub Desktop.
Save codepainkiller/ceb538a8a8aa099a1fdd04f6b1d751f4 to your computer and use it in GitHub Desktop.
Final Exam M101P
// Question 1
db.messages.find({
$and: [
{"headers.From": "andrew.fastow@enron.com"},
{"headers.To": {$in: ["jeff.skilling@enron.com"]}}
]
}).count();
// Question 2
db.messages.aggregate([
{
$project: {
"message_id": "$headers.Message-ID",
"from": "$headers.From",
"to": "$headers.To"
}
},
{
"$unwind": "$to"
},
{
"$group":{
"_id": {
"message_id": "$message_id",
"from": "$from"
},
"to": {"$addToSet": "$to"}
}
},
{
"$unwind": "$to"
},
{
"$group":{
"_id": {
"from": "$_id.from",
"to": "$to"
},
"count": {$sum: 1}
}
},
{
"$sort": {"count": -1}
}
])
// Question 3
// Validation code: vOnRg05kwcqyEFSve96R
db.messages.update(
{
"headers.Message-ID": "<8147308.1075851042335.JavaMail.evans@thyme>"
},
{
$push: {"headers.To": "mrpotatohead@mongodb.com"}
}
)
# Martin Cruz
# martincruz.me - Copyright 2016, All Rights Reserved
import pymongo
import datetime
import sys
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.final7
def remove_image(image_id):
images = db.images
try:
result = images.delete_one({'_id': image_id})
print "num removed: ", result.deleted_count
except Exception as e:
print "Exception: ", type(e), e
def exists_in_album(image_id):
albums = db.albums
try:
count = albums.find({'images': {'$all': [image_id]}}).count()
if count > 0:
return True
return False
except Exception as e:
print "Exception: ", type(e), e
def find_images():
images = db.images
try:
docs = images.find()
count = 0
for doc in docs:
if not exists_in_album(doc['_id']):
count += 1
remove_image(doc['_id'])
except Exception as e:
print "Exception: ", type(e), e
print "Images removed: ", count
find_images()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment