嵌入式文档中的MongoDB / MongoMapper修饰符

时间:2011-06-28 02:14:41

标签: ruby-on-rails 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的嵌入式文档来实现这一点。关于我做错了什么的想法?

1 个答案:

答案 0 :(得分:2)

这对任何有兴趣的人都有用。我失踪的两件事

  1. 使用$elemMatch搜索数组中需要满足两个条件的对象(例如_id =“”AND选民不包含user_id)
  2. $$inc操作上使用$push运算符,以确保我正在修改查询引用的特定对象。

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