How to delete an Embedded Doc in MongoMapper using atomic Pull?
I'm successfully using MongoMapper's built-in support for atomic "$push" and "$set", but can't figure out "$pull"
class Feed
include MongoMapper::Document
many :stories
end
class Story
include MongoMapper::EmbeddedDocument
key :title, String
end
feed = Feed.first
story = Story.new(:title => "Hello, world!")
Feed.push(feed.id开发者_Go百科, :stories => story.to_mongo) #works fine
Feed.set({:_id => feed.id, "stories.title" => "Hello, world!"}, "stories.$.title" => "Foo") #works fine
Feed.pull( ??? )
How can I atomically remove a story using pull?
To atomically remove an embedded document using simply the parent id and the child id you can do this:
Feed.pull(feed.id, :stories => {:_id => story.id})
If you already have the parent doc, you can do this instead:
feed.pull(:stories => {:_id => story.id})
Now I feel embarrassed for asking the question (and answering it). This is pretty straightforward.
精彩评论