模块:Mongoid::Persistable::Upsertable

包含在:
Mongoid::Persistable
定义于:
lib/mongoid/persistable/upsertable.rb

Overview

定义更新或插入(upsert)文档的持久性操作的行为。

实例方法摘要折叠

实例方法详细信息

# 更新或插入(upsert) (options = {}) ⇒ true

对文档执行更新或插入(upsert)或插入。 如果数据库中不存在该文档,则mongo将插入一个新文档,否则字段将被现有文档上的新值覆盖。

如果替换选项为 true,则删除未指定的属性;如果为 false,则保留未指定的属性。 在 Mongoid 9中,替换选项默认为 false。

例子:

更新或插入文档。

document.upsert

使用替换更新或插入文档。

document.upsert(replace: true)

使用插入时使用的额外的属性进行更新或插入。

document.upsert(set_on_insert: { created_at: DateTime.now })

参数:

  • 选项 哈希 (默认为: {}

    验证选项。

选项哈希 ( options ):

  • :validate ( true | false )

    是否进行验证。

  • :replace ( true | false )

    是否在更新或更新或插入(upsert)时替换文档。

  • :set_on_insert 哈希

    在文档尚不存在的情况下要包含的属性。

返回:

  • ( true )

    是的。



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/mongoid/persistable/upsertable.rb', line 36

def 更新插入(选项 = {})
  prepare_upsert(选项) do
    if 选项[:replace]
      if 选项[:set_on_insert]
        提高 ArgumentError, "无法指定 :set_on_insert with `replace: true` "
      end

      集合.find(atomic_selector).replace_one(
        as_attributes, 更新或插入: true, 会话: _session)
    else
      attrs = { " $set " => as_attributes }
      attrs["$setOnInsert"] = 选项[:set_on_insert] if 选项[:set_on_insert]

      集合.find(atomic_selector).update_one(
        attrs, 更新或插入: true, 会话: _session)
    end
  end
end