I have mongo_mapper set up like so:
class Person
include MongoMapper::Document
many :pets
end
class Pet
include MongoMapper::EmbeddedDocument
key :animal, String
key :name, String
key :colour, String
end
# Create a person
me = Person.new
# Add pets to the person
me.pets << Pet.new(:animal => 'dog',:name => 'Mr. Woofs', :colour => 'golden')
me.pets << Pet.new(:animal => 'cat', :name => 'Kitty', :colour => 'black')
me.pets << Pet.new(:animal => 'cat', :name => 'Freckles', :colour => 'black')
me.pets << Pet.new(:animal => 'cat', :name => 'Fluffy', :colour => 'tabby')
I know I can delete all pets very simply (me.pets
works as an array but also calls back)
# Delete all pets
me.pets.clear
I also know that I could delete all black cats by doing this:
# Delete black cats
me.pets.delete_if {|pet| pet.animal == 'cat' and pet.colour = 'black'}
But that seems like it'll take a very long time if there are a large number of pets to iterate through.
I feel like there should be a way to select only the black cats and then clear
that array instead. Is there such a way?