2010-08-29 50 views
0

我已經mongo_mapper設置像這樣:與蒙戈映射刪除EmbeddedDocuments

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') 

我知道我可以刪除很乾脆所有的寵物(me.pets作品作爲數組也回調)

# Delete all pets 
me.pets.clear 

我也知道我可以這樣做刪除所有的黑貓:

# Delete black cats 
me.pets.delete_if {|pet| pet.animal == 'cat' and pet.colour = 'black'} 

但似乎如果需要大量寵物進行迭代,則需要很長時間。

我覺得應該有一種方法只選擇黑貓,然後用數組代替clear。有沒有這樣的方式?

回答

0

嘗試這樣的事情,不知道這會工作,但值得一試。

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

說實話,雖然我認爲你對此沒有任何擔心。通常數組操作很快。

+0

我很欣賞這個回答,但不幸的是:'NoMethodError:undefined method'all'for []:Array'。我知道像這樣的集合在數組上迭代不會花費大量時間,但我期望一次處理10,000個嵌入文檔的順序,並且最多隻需要刪除約10個! – 2010-08-31 21:00:41

+1

JP,你會花多長時間用你知道截至目前爲止最快的方式清空1000個嵌入式文檔? – 2011-02-23 04:57:26