Railsã§MongoDBã使ã£ãã¢ããªã³ã°
Ruby MongoDB Driver — Ruby Driver Manual 2.8
- JOIN ãã§ããªãã®ã§ããã£ãã·ã¥ã§ãã¾ããã¨ããï¼
Caching to Avoid N+1
When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.
- N 対 N ã®ãã¼ã¿ã«å¯¾ãã¦ãRDBã ã¨ä¸éãã¼ãã«ãä½ã£ããããããããã¥ã¡ã³ã(like a ãªãã¸ã§ã¯ã) æ¹å¼ã ã¨ããç´æçã«ãã¼ã¿ã«ã¢ã¯ã»ã¹ã§ãã
Fields as arrays
With a relational database, even trivial relationships are blown out into multiple tables. Consider the votes a story receives. We need a way of recording which users have voted on which stories. The standard way of handling this would involve creating a table, 'votes', with each row referencing user_id and story_id.
With a document database, it makes more sense to store those votes as an array of user ids, as we do here with the 'voters' key.
To find all the stories voted on by a given user: Story.all(:conditions => {:voters => @user.id})
- ã¢ãããã¯ãªã¢ãããã¼ãã®å®ç¾æ¹æ³
#ãstoriesãã³ã¬ã¯ã·ã§ã³ã«ã¢ãããã¼ã db.stories.update( # voters é åã«user_id ãå«ã¾ãªãè¨äºããã {_id: story_id, voters: {'$ne': user_id}}, # ããããã°ãvotes ã +1 ãã¦ãvoters é åã«user_id ã追å ãã {'$inc': {votes: 1}, '$push': {voters: user_id}});
- æ°ãã¤ããªãããããªãã®ã¯ãupdate ã¯åºæ¬ãå®è¡ãããããå¿ããããã¬ã¹ãã³ã¹ã¯è¿ããªããã¾ãã»ã¨ãã©ã®å ´åã§åé¡ãªãã ãããã©ããã¨ã®ãã¨
The one caveat is that, because update operations are "fire and forget," you won't get a response from the server. But in most cases, this should be a non-issue.
- åºæ¬ç㪠1 対 N ã®é¢ä¿ã«ãããã¼ã¿ã¯é åã§ä¿æãããã¹ã
Essentially, comments are represented as an array of objects within a story document. This simple structure should be used for any one-to-many relationship where the many items are linear.
- ã³ã¡ã³ãã®ãã¹ãããã¾ã使ãã°ããããããã ãªã
@stories = @db.collection('stories') @document = {:title => "MongoDB on Rails", :comments => [{:body => "Revelatory! Loved it!", :username => "Matz", :comments => [{:body => "Agreed.", :username => "rubydev29" } ] } ] } @stories.save(@document)