Last active
December 25, 2015 20:19
-
-
Save jeffyuhaoliu/7034252 to your computer and use it in GitHub Desktop.
MongoDB & Node.js Class Finals 7 - Your task is to write a program to remove every image from the images collection that appears in no album. Or put another way, if an image does not appear in at least one album, it's an orphan and should be removed from the images collection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use photosharing | |
db.images.aggregate([ | |
{ | |
$unwind: "$tags" | |
}, | |
{ | |
$match: { tags: 'kittens'} | |
}, | |
{ | |
$group: { | |
_id: null, | |
count: { $sum: 1 } | |
} | |
} | |
]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function filter(image) { | |
if (db.albums.count({'images': image._id}) == 0) | |
{ | |
db.images.remove({'_id': image._id}); | |
} | |
}; | |
function map() { | |
emit('_id', this._id); | |
} | |
function reduce(key, values) { | |
var result = 0; | |
if (key === '_id') { | |
for(var i = 0; i < values.length; i++) | |
{ | |
result += values[i]; | |
} | |
} | |
return result; | |
} | |
use photosharing; | |
db.images.find().forEach(filter); | |
db.images.mapReduce(map, reduce, {out: {inline: 1}}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment