views:

14

answers:

1

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?

A: 

try something like this, no idea if this'll work but worth a shot.

me.pets.all(:animal => "cat", :colour => "black").clear

To be honest though I think you are worrying about this for nothing. Usually array manipulation are plenty fast.

Hugo
I appreciate the response but unfortunately: `NoMethodError: undefined method ‘all’ for []:Array`. I get that for collections like this iterating over an array is not going to take a large amount of time, but I'm expecting to be dealing with the order of 10,000 embedded documents at a time, and only needing to delete at most ~10!
JP