「SequoiaDB巨杉数据库」upsert()概述3

错误

错误信息记录在节点诊断日志(diaglog)中,可参考错误码

示例

假设集合 employee 中有两条记录:

{
  "_id": {
    "$oid": "516a76a1c9565daf06030000"
  },
  "age": 10,
  "name": "Tom"
}
{
  "_id": {
    "$oid": "516a76a1c9565daf06050000"
  },
  "a": 10,
  "age": 21
}

按指定的更新规则更新集合中所有记录,即设置 rule 参数,不设定 cond 和 hint 参数的内容。如下操作等效于使用 update 方法,更新集合 employee 中的所有记录,使用$inc将记录的 age 字段值加1,name 字段值更改为“Mike”,对不存在 name 字段的记录,$set 操作符会将 name 字段和其设定的值插入到记录中,可使用 find 方法查看更新结果。

db.sample.employee.upsert( { $inc: { age: 1 }, $set: { name: "Mike" } } )
{
"UpdatedNum": 2,
"ModifiedNum": 2,
"InsertedNum": 0
}
>
db.sample.employee.find()
{
  "_id": {
  "$oid": "516a76a1c9565daf06030000"
  },
  "age": 11,
  "name": "Mike"
}
{
  "_id": {
  "$oid": "516a76a1c9565daf06050000"
  },
  "a": 10,
  "age": 22,
  "name":"Mike"
}
Return 2 row(s).

按访问计划更新记录,假设集合中存在指定的索引名 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).

分区集合 sample.employee,分区键为 { a: 1 },含有以下记录

db.sample.employee.find()
{
"_id": {
 "$oid": "5c6f660ce700db6048677154"
},
"a": 1,
"b": 1
}
Return 1 row(s).

指定 KeepShardingKey 参数:不保留更新规则中的分区键字段。只更新了非分区键 b 字段,分区键 a 字段的值没有被更新。

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
Sharding key cannot be updated

点击巨杉数据库文档中心了解更多信息

猜你喜欢

转载自blog.csdn.net/weixin_45890253/article/details/112984025
今日推荐