summaryrefslogtreecommitdiff
path: root/week-7/final7/solve.rb
blob: fff2a2f5eb55eeccee5b8f16a93e6f8e7612187f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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