嵌入或引用关系 [英] Embedded or referenced relations

查看:49
本文介绍了嵌入或引用关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mongodb和mongoid宝石,我想得到一些建议.

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

我有一个应用程序,其中用户has many市场和市场has many产品. 我需要在属于用户的所有(或任何)市场中搜索特定价格范围内的产品.

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)

我很好奇,因为mongdb是一个面向文档的数据库,如果在这种情况下使用嵌入式文档,我会在性能或设计上受益吗?

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?

推荐答案

在您的情况下,我建议您使用引用的数据.因为我想您需要自己操作这些集合中的每个集合(您需要能够通过_id编辑/删除/更新产品",并执行其他一些复杂的查询,当您单独进行查询时,这将更加容易且有效收藏).

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).

同时,我会将 some 个完整的嵌入式数据存储在Users集合中,以加快向访问者的浏览器显示的速度.假设您有一个用户页面,要在其中显示用户个人资料以及排名前5位的市场和排名前20位的产品.您可以将最新的top-5和top-20嵌入到用户文档中,并在有新市场/产品时更新这些嵌入的对象.在这种情况下-当显示用户页面时,您只需对MongoDB进行1次查询.因此,它可以用作缓存.如果访问者需要查看更多产品,请转到下一页产品",并在MongoDB中查询单独的产品"集合.

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.

这篇关于嵌入或引用关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆