diff options
| author | mo khan <mo@mokhan.ca> | 2015-02-21 21:51:33 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2015-02-21 21:51:33 -0700 |
| commit | 320e98ab7d012a47c9bb594622ea91e57a2c0e1f (patch) | |
| tree | 39ac1e5b956ccfb865170fb2db12e6489f4b38f2 | |
| parent | d7e75d21686d847ff53c9608f7df960f5c6365a7 (diff) | |
write script to delete unused images.
| -rw-r--r-- | week-7/final7/solve.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/week-7/final7/solve.rb b/week-7/final7/solve.rb new file mode 100644 index 0000000..fff2a2f --- /dev/null +++ b/week-7/final7/solve.rb @@ -0,0 +1,34 @@ +require 'rubygems' +require 'bundler' +Bundler.require + +def main + client = Mongo::MongoClient.new + db = client['final7'] + images_collection = db['images'] + albums_collection = db['albums'] + + albums = albums_collection.aggregate([ + { '$unwind': '$images' }, + { '$project': { '_id': '$images' } }, + { '$group': { '_id': '$_id', count: { '$sum': 1 } } }, + ]) + used_images = albums.reduce({}) do |memo, image| + memo[image['_id']] = true + memo + end + images = images_collection.find().to_a + deleted = 0 + images.each do |image| + image_id = image['_id'] + if used_images.key?(image_id) == false + puts "Deleting: #{image_id}" + #images_collection.remove("_id": image_id) + deleted += 1 + end + end + puts "USED: #{used_images.size}" + puts "DELETED: #{deleted}" +end + +main |
