Skip to content

Instantly share code, notes, and snippets.

@jeffyuhaoliu
Last active December 25, 2015 20:19
Show Gist options
  • Save jeffyuhaoliu/7034252 to your computer and use it in GitHub Desktop.
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.
use photosharing
db.images.aggregate([
{
$unwind: "$tags"
},
{
$match: { tags: 'kittens'}
},
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
])
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