upsert()
更新集合记录。upsert 方法跟 update 方法都是对记录进行更新,不同的是当使用 cond 参数在集合中匹配不到记录时,update 不做任何操作,而 upsert 方法会做一次插入操作。
参数描述
返回值
成功返回详细结果信息(BSONObj 对象),结构如下:
出错抛异常,并输出错误信息,可以通过getLastErrMsg()获取错误信息或通过获取错误信息码。错误信息对象包括详细结果信息。
错误信息记录在节点诊断日志(diaglog)中,可参考错误码。
示例
假设集合 employee 中有两条记录:
{
"_id": {
"$oid": "516a76a1c9565daf06030000"
},
"age": 10,
"name": "Tom"
}
{
"_id": {
"$oid": "516a76a1c9565daf06050000"
},
"a": 10,
"age": 21
}
-
> db.sample.employee.upsert( { $inc: { age: 1 }, $set: { name: "Mike" } } )
{
"UpdatedNum": 2,
"ModifiedNum": 2,
"InsertedNum": 0
}
>
> db.sample.employee.find()
{
"$oid": "516a76a1c9565daf06030000"
},
"age": 11,
"name": "Mike"
{
"_id": {
"$oid": "516a76a1c9565daf06050000"
},
"a": 10,
"age": 22,
"name":"Mike"
}
Return 2 row(s).
选择符合匹配条件的记录,对这些记录按更新规则更新,即设定 rule 和 cond 参数。如下操作使用$exists匹配存在 type 字段的记录,使用将这些记录的 age 字段值加3。在上面给出的两条记录中,都没有 type 字段,此时,upsert 操作会插入一条新的记录,新记录只有 _id 字段和 age 字段名,_id 字段值自动生成,而 age 字段值为3。
按访问计划更新记录,假设集合中存在指定的索引名 testIndex,此操作等效于使用 update 方法,使用索引名为 testIndex 的索引访问集合 employee 中 age 字段值大于20的记录,将这些记录的 age 字段名加1。
> db.sample.employee.upsert( { $inc: { age: 1 } }, { age: { $gt: 20 } }, { "": "testIndex" } )
{
"UpdatedNum": 1,
"ModifiedNum": 1,
"InsertedNum": 0
}
>
> db.sample.employee.find()
{
"_id": {
"$oid": "516a76a1c9565daf06050000"
},
"a": 10,
"age": 23,
"name":"Mike"
}
Return 1 row(s).
使用setOnInsert更新记录,由于集合 employee 中 age 字段值大于30的记录为空,upsert在做插入操作时向插入的记录中追加字段{“name”:”Mike”}。
> db.sample.employee.upsert( { $inc: { age: 1 } }, { age: { $gt: 30 } }, {}, { "name": "Mike" } )
"UpdatedNum": 0,
"ModifiedNum": 0,
}
>
> db.sample.employee.find( { "age" : 1, "name": "Mike" } )
{
"_id": {
"$oid": "516a76a1c9565daf06050000"
},
"age":1,
"name":"Mike"
}
Return 1 row(s).
分区集合 sample.employee,分区键为 { a: 1 },含有以下记录
-
> db.sample.employee.upsert( { $set: { a: 9, b: 9 } }, {}, {}, {}, { KeepShardingKey: false } )
{
"UpdatedNum": 1,
"ModifiedNum": 1,
"InsertedNum": 0
}
>
> db.sample.employee.find()
{
"_id": {
"$oid": "5c6f660ce700db6048677154"
},
"a": 1,
"b": 9
}
Return 1 row(s).
指定 KeepShardingKey 参数:保留更新规则中的分区键字段。因为目前不支持更新分区键,所以会报错。
> db.sample.employee.upsert( { $set: { a: 9 } }, {}, {}, {}, { KeepShardingKey: true } )
(nofile):0 uncaught exception: -178