Embedded or referenced relations

2019-07-19 17:21发布

I use mongodb and mongoid gem and I'd like to get some advice.

I have an app where User has many Markets and Market has many Products. I need to search for the products, say in a specific price range, in all (or any) the markets which belong to the user.

Which relation fits better for this, embedded or referenced?

I currently use referenced and it looks like so

class User
  has_many :markets
end

class Market
  belongs_to :user
  has_many :products
end

class Product
  belongs_to :calendar
  belongs_to :user
end

And for search, I use this query

Product.where(user_id: current_user.id).
  in(market_id: marked_ids).
  where(:price.gte => price)

I'm curious, since mongdb is a document oriented database, would I benefit in a performance or design, if I used embedded documents in this situation?

2条回答
2楼-- · 2019-07-19 17:46

In your case I would advice to use referenced data. Because I suppose that you need to manipulate each of those collections on it's own (you need to be able to edit/delete/update "products" by _id, and do some other complicated queries, which is much easier and effective when you have separate collection).

At the same time I would store some full embedded data in Users collection, just for speed-up display to visitor's browser. Let's say you have a user's page where you want to show user's profile and top-5 markets and top-20 products. You can embed those newest top-5 and top-20 to User's document and update those embedded objects when there are new markets/products. In this case - when you show user's page you need to make just 1 query to MongoDB. So this works as cache. If visitor needs to view more products, he goes to the next page "Products" and query separate "Products" collection in MongoDB.

查看更多
在下西门庆
3楼-- · 2019-07-19 17:46

Use embedded documents if you only need to access the item through the parent class. If you need to query it directly or from multiple objects, use a reference.

查看更多
登录 后发表回答