MongoDB update setOnInsert

MongoDB update setOnInsert

MongoDBupdate 方法当指定 setOnInsert 参数时,如果 upsert 设为true。当满足查询条件的记录存在,则不执行 $setOnInsert 中的操作,当满足条件的记录不存在则执行 $setOnInsert 操作。

与 $set 指令配合使用,可以作为 $set 指令的补充。当满足查询条件的记录存在,则执行 $set 操作,当满足查询条件的记录不存在,则新增一条记录,其中包含 $set 指令设置的属性以及 $setOnInsert 指令设置的属性。

MongoDB update setOnInsert详解

语法

db_name.collection_name.update( <query>, { $setOnInsert: { <field1>: <value1>, ... } }, { upsert: true } )

参数

参数 描述
db_name 数据库名
collection_name 集合名
query 必选项,是设置更新的文档的条件
setOnInsert 要插入的字段
update 为更新操作符

案例

mongodb update setOnInsert

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

73_mongodb update setOnInsert.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insert 插入记录,具体命令如下:

db.haicoder.insert({"name":"haicoder", "url":"www.haicoder.net"})

执行完毕后,我们再次使用 find 查看当前的所有记录,如下图所示:

74_mongodb update setOnInsert.png

我们看到,此时提示我们成功插入了一条记录,现在,我们再次使用 update 加上 setOnInsert 更新这条记录,具体命令如下:

db.haicoder.update({"name":"haicoder"}, {$set:{age:100}, $setOnInsert:{online:1}}, {upsert:true})

执行完毕后,我们再次使用 find 查看当前的所有记录,如下图所示:

75_mongodb update setOnInsert.png

我们看到,此时的 name 为 haicoder 的记录是存在的,因此,这里仅仅插入了 age 字段,并没有插入 online 字段,现在,我们更新一条不存在的记录,具体命令如下:

db.haicoder.update({"name":"HAICODER"}, {$set:{age:100}, $setOnInsert:{online:1}}, {upsert:true})

执行完毕后,我们再次使用 find 查看当前的所有记录,如下图所示:

76_mongodb update setOnInsert.png

我们看到,此时的 name 为 HAICODER 的记录是不存在的,因此,插入了 name 字段和 age 字段已经 online 字段。

MongoDB update setOnInsert总结

MongoDB 的 update 方法当指定 setOnInsert 参数时,如果 upsert 设为true。当满足查询条件的记录存在,则不执行 $setOnInsert 中的操作,当满足条件的记录不存在则执行 $setOnInsert 操作。

与 $set 指令配合使用,可以作为 $set 指令的补充。当满足查询条件的记录存在,则执行 $set 操作,当满足查询条件的记录不存在,则新增一条记录,其中包含 $set 指令设置的属性以及 $setOnInsert 指令设置的属性。