使用 Mongo Mapper 删除 EmbeddedDocuments

发布于 2024-09-16 14:36:25 字数 1034 浏览 3 评论 0原文

我已经像这样设置了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳絮泡泡 2024-09-23 14:36:25

尝试这样的事情,不知道这是否有效,但值得一试。

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

说实话,我认为你担心这个是多余的。通常数组操作非常快。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文