【问题标题】:How to do an upsert / push with mongoid / moped如何使用 mongoid / moped 进行 upsert / push
【发布时间】:2012-07-17 19:58:12
【问题描述】:

我正在使用 Mongoid (v3) 访问 MongoDB,并希望执行此操作:

db.sessionlogs.update( 
    {sessionid: '12345'}, /* selection criteria */
    {'$push':{rows: "new set of data"}},  /* modification */
    true /* upsert */
);

这在 mongo shell 中运行良好。这也正是我想要的,因为它是一个单一的原子操作,这对我来说很重要,因为我会经常称呼它。我不想做两个操作——一个获取然后一个更新。我通过 mongoid 尝试了很多东西,但无法让它工作。

我怎样才能让 MongoID 不碍事,只需将此命令发送到 MongoDB?我猜想在 Moped 级别有一些方法可以做到这一点,但该库的文档基本上不存在。

【问题讨论】:

标签: ruby mongodb mongoid mongoid3 moped


【解决方案1】:

暂时先别小看 moped,您可以使用 find 和 modify 操作来实现相同的目的(使用所有默认范围和继承的好东西)

如果不存在,则在图中保存边的示例

edge = {source_id: session[:user_id],dest_id:product._id, name: edge_name}
ProductEdge.where(edge).find_and_modify(ProductEdge.new(edge).as_document,{upsert:true})

【讨论】:

    【解决方案2】:

    这是一种方法:

    session_log = SessionLog.new(session_id: '12345') session_log.upsert session_log.push(:rows, "新数据集")

    或者其他:

    SessionLog.find_or_create_by(session_id: '12345')。 push(:rows, "新数据集")

    #push 在字段上执行原子$push。上面有解释 Atomic Persistence页面。

    (注意:示例使用 UpperCamelCase 和 snake_case 与 Ruby 约定一样。)

    【讨论】:

      【解决方案3】:

      [在写问题时找到答案...]

      criteria = Sessionlogs.collection.find(:sessionid => sessionid)
      criteria.upsert("$push" => {"rows" => datarow})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-30
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2013-06-23
        相关资源
        最近更新 更多