Created
November 6, 2010 20:04
-
-
Save wxmn/665675 to your computer and use it in GitHub Desktop.
Examples of Atomic Operations on Embedded Documents in MongoMapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Stories are embedded docs in a Feed | |
class Feed | |
include MongoMapper::Document | |
many :stories | |
end | |
class Story | |
include MongoMapper::EmbeddedDocument | |
key :title, String | |
key :posted_by, String | |
end | |
#create a feed | |
feed = Feed.create | |
#the standard way to add an embedded doc | |
story1 = Story.new(:title => "Coding", :posted_by => "Michael") | |
feed.stories << story1 | |
feed.save! #this saves the entire feed document | |
#atomically add an embedded doc | |
story2 = Story.new(:title => "Eating", :posted_by => "Josh") | |
Feed.push(feed.id, :stories => story2.to_mongo) | |
## adds this story to the feed | |
#you can also do it this way if you already have the feed | |
story3 = Story.new(:title => "Sleeping", :posted_by => "Josh") | |
feed.push(:stories => story3.to_mongo) | |
#atomically remove an embedded doc | |
Feed.pull(feed.id, {:stories => {:posted_by => "Josh"}}) | |
## removes all stories posted by Josh | |
#atomically edit an embedded doc | |
Feed.set({:_id => feed.id, "stories.title" => "Coding"}, "stories.$.title" => "Hacking") | |
## edits the title of the FIRST story with a title of "Coding" to "Hacking" | |
## notice the "dot" notation for getting to fields | |
## and the position element ("$"), which returns the *FIRST* of the documents returned in the query | |
## this example makes sense for manipulating single embedded documents, but to update multiple ones | |
## it probably makes more sense to use Ruby Array/Enumerable and save the whole document | |
## I've just been fiddling with this for the past day or so, so if I'm doing something wrong | |
## (or if there's a better way to do some of this stuff), please let me know! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful. Thank you~