【问题标题】:Will looking up parent document cause an extra query call?查找父文档会导致额外的查询调用吗?
【发布时间】:2013-07-18 18:27:53
【问题描述】:

我有两个模型。

class User
  include Mongoid::Document

  field :name, type: String

  embeds_many :posts
end

class Post
  include Mongoid::Document

  field :comment, type: String

  embedded_in :user
end

现在假设我得到了第一个用户的第一个帖子,然后我调用了用户的名字。这会导致调用额外的查询,还是父文档是帖子的一部分?

posts = User.first.posts

first_post = posts.first

# Will this line of code below initiate a query search for users?
users_name = first_post.user.name

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid associations


    【解决方案1】:

    按照设计,MongoDB 一次只允许从一个集合中检索文档。因此,如果Post 位于与Users 不同的集合中,则需要两个查询。虽然可以缓存给定文档(无需进行第二次查询),但假设通常会进行两次查询。

    MongoDB 的某些驱动程序尝试使用 $in 运算符为单个集合收集多个记录(例如 Posts)。此外,你可以使用 Mongoid extras 缓存功能进行一些预取/缓存:http://mongoid.org/en/mongoid/docs/extras.html#caching

    当使用嵌入文档时,整个文档实际上是在上面显示的查询中获取的,因此不需要第二次查询来获取名称。

    # the entire User object matching the statement is fetched (the first User)
    posts = User.first.posts  
    # nothing happens here ... just client side
    first_post = posts.first
    
    # No, this won't result in a second query, as the entire document was fetched
    users_name = first_post.user.name
    

    【讨论】:

    • 嵌入文档也是这样吗?我在想嵌入文档与父文档物理位置相同。但我想如果我调用嵌入文档,父文档不会被传递到指向嵌入文档的变量。
    • 抱歉,忘记添加了!添加了详细信息 - 一次全部加载,因此没有第二次查询。
    • 谢谢。我现在明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2014-03-21
    • 2016-03-24
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多