2011-06-28 41 views
1

需要一些关于如何在嵌入式文档上使用原子修饰符的帮助。关于嵌入式文档的MongoDB/MongoMapper修饰符

为了说明,我们假设我有一个看起来像这样的集合。

帖子收藏

{ 
    "_id" : ObjectId("blah"), 
    "title" : "Some title", 
    "comments" : [ 
    { 
     "_id" : ObjectId("bleh"), 
     "text" : "Some comment text", 
     "score" : 0, 
     "voters" : [] 
    } 
    ] 
} 

我正在寻找与MongoMapper/MongoDB的做的是后文件中的特定评论进行原子更新。

喜欢的东西:

class Comment 
    include MongoMapper::EmbeddedDocument 

    # Other stuff... 

    # For the current comment that doesn't have the current user voting, increment the vote score and add that user to the voters array so they can't vote again 
    def upvote!(user_id) 
    collection.update({"comments._id" => post_id, "comments.voters" => {"$ne" => user_id}}, 
     {"$inc" => {"comments.score" => 1}, "$push" => {"comments.voters" => user_id}}) 
    end 
end 

这基本上就是我现在并没有在所有工作(没有被更新)。理想情况下,我也想重新加载文档/嵌入式文档,但似乎没有办法使用MongoMapper的嵌入式文档来完成此操作。任何想法,我做错了什么?

回答

2

得到这个工作对任何有兴趣的人。有两件事情我是缺少

  1. 使用$elemMatch到需要满足两个条件(如_id =“”和选民不包含USER_ID)
  2. 使用$操作上$inc阵列中搜索对象和$push操作来确保我正在修改我的查询引用的特定对象。

def upvote!(user_id) 
    # Use the Ruby Mongo driver to make a direct call to collection.update 
    collection.update(
    { 
     'meanings' => { 
     '$elemMatch' => { 
      '_id' => self.id, 
      'voters' => {'$ne' => user_id} 
     } 
     } 
    }, 
    { 
     '$inc' => { 'meanings.$.votes' => 1 }, 
     '$push' => { 'meanings.$.voters' => user_id } 
    }) 
end