2013-02-13 91 views
0

我在使用Mongoid和MongoDB创建应用程序。我有了一个轮廓像这样一个用户:Mongoid Map使用has_one减少

class User 

field :email, :type => String 
field :name, :type => String 
field :date_of_birth, :type => DateTime 
has_one :profile 

end 

class Profile 

field :votes, :type => Hash 
field :biography, :type => String 
belongs_to :profile 

end 

的票散的结构,像这样:

profile : { 
    "user_id" : ObjectId("511b76b0e80c505750000031"), 
    "votes": { 
    "vote_count": 3, 
    "up_votes": 3, 
    "down_votes": 0 
    } 
} 

我运行图减少,像这样:

map = " 
    function() { 
    values = { 
     name: this.name 
    } 
    emit(this._id, values); 
    } 
" 

reduce = " 
    function (key, emits) { 
    return emits; 
    } 
" 

User.map_reduce(map, reduce).out(replace: "leaderboards").each do |document| 
    ap document 
end 

该作品罚款并在Mongo中创建一个名为排行榜的新集合。不过,我试图从配置文件中映射一些数据,因此它包含配置文件中的vote_count字段。

从根本上让我的地图功能看起来像这样:

map = " 
    function() { 
    values = { 
     name: this.name, 
     votes: this.profile.votes.vote_count 
    } 
    emit(this._id, values); 
    } 
" 

但是我有困难拿到与用户相关的配置文件。有谁知道我如何从用户配置文件中提取数据?

如果有什么不明白的地方让我知道。任何帮助,将不胜感激。

托尼

回答

1

存在的MongoDB没有办法的事“加入”从服务器端的不同集合的数据 - 你必须做他们在您的客户端应用程序,或者更好的,考虑document embedding,尤其是在目前是您的用户和个人资料集合之间的1:1关系。现在

,如果设计变化是不是一种选择,你可以按顺序执行两个MapReduce的():

  1. 一个你有用户,但使用USER_ID为重点,并添加名称 作为现场
  2. 在档案MapReduce的具有相同USER_ID键和 vote_count,指定merge output到您的排行榜 收集

这是否帮助?

问候

罗纳德