使用 Mongo Mapper 删除 EmbeddedDocuments
我已经像这样设置了 mongo_mapper:
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'}
但是如果有大量宠物需要迭代,那么似乎需要很长时间。
我觉得应该有一种方法可以只选择黑猫,然后清除
那个数组。有这样的办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这样的事情,不知道这是否有效,但值得一试。
说实话,我认为你担心这个是多余的。通常数组操作非常快。
try something like this, no idea if this'll work but worth a shot.
To be honest though I think you are worrying about this for nothing. Usually array manipulation are plenty fast.