MongoDB 文档的更新操作

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介:

在MongoDB中,更新单个doc的操作是原子性的。默认情况下,如果一个update操作更新多个doc,那么对每个doc的更新是原子性的,但是对整个update 操作而言,不是原子性的,可能存在前面的doc更新成功,而后面的doc更新失败的情况。由于更新单个doc的操作是原子性的,如果两个更新同时发生,那么一个更新操作会阻塞另外一个,doc的最终结果值是由时间靠后的更新操作决定的。

通过使用 $isolated option,能够确保更新多个doc的写操作是原子性的,任何查询操作都会读取到更新操作,直到该操作完成(成功或失败)。 

Prevents a write operation that affects multiple documents from yielding to other reads or writes once the first document is written. By using the $isolated option, you can ensure that no client sees the changes until the operation completes or errors out.

MongoDB在新增和更新数据的时候,不会实时写入到Disk中,可能会丢失数据。

一,语法

默认情况下,update只会更新single doc,如果需要更新多个doc,必须显式设置doc: multi:true。

复制代码
db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)
复制代码

upsert:Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

multi:Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false.

二,更新示例

在users collection中有三个doc,插入代码如下

user1={ name:"t1", age:21}
user2={ name:"t2", age:22}
user3={ name:"t3", age:23}

db.users.insert([user1,user2,user3])

1,upsert option usage

upsert option的含义是,如果collection中存在匹配的doc,那么更新该doc;如果不匹配任何doc,那么插入一条新的doc。

使用update命令和 upsert选项,插入一条新的user,name=“t4”

db.users.update({name:"t4"},{name:"t4"},{upsert:true})

对新插入的user新增field:age=24,必须将doc的所有field都显式指定。

db.users.update({age:24},{name:"t4",age:24})

如果在Update doc中,只包含age=24,那么将失去name field,例如

 db.users.update({name:"t4"},{age:24})

2,multi option usage

在使用multi option更新多个doc之前,先考虑一个问题,如果把age的年纪都加1,那么在age加1时,保持其他field不变。这种情况需要用到$inc operator,用于将指定字段的值递增,同时不会影响其他字段。

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

示例,将符合条件的User的age 加 1

db.users.update({age:{$lt:24}},{$inc:{age:1}},{multi:true})

3,为所有的user 增加字段

这种scenario需要用到$set operator,用于替换指定字段的值,或新增字段。

{ $set: { <field1>: <value1>, ... } }

The $set operator replaces the value of a field with the specified value. If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

示例,为所有的user增加sex字段,默认值是femal。

db.users.update({},{$set:{sex:"femal"}},{multi:true})

三,原子更新multiple doc

在query filter中加入 $isolated:1,表示对于查询到的所有doc,update操作将会在一个原子操作中完成。

db.users.update({$isolated:1},{$set:{sex:"femal"}},{multi:true})

四,更新doc的结构

1,将doc的sex field删除

Step1,使用FindOne找到name=t4的User

t4=db.users.findOne({name:"t4"})

Step2,使用delete command 删除sex field

delete t4.sex;

Step3,使用Updae 替换原来的doc

 db.users.update({name:"t4"},t4);

step4,使用find 查看doc的数据更新

2,使用db.collection.replaceOne替换doc

复制代码
db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>
   }
)
复制代码

step1,使用findOne()查找一个doc

 t4=db.users.findOne({name:"t4"})

step2,为doc增加一个sex field

t4.sex="femal"

step3,使用replaceOne函数替换doc

db.users.replaceOne({name:"t4"},t4)

3,使用$set对所有符合query filter的doc批量修改doc结构

db.users.update({age:{$lte:23,$gte:21}},{$set:{sex:"femal"}},{multi:true});

4,使用$unset对所有符合query filter的doc批量删除doc的field

db.users.update({$and:[{age:{$lte:23}},{age:{$gte:21}}]},{$unset:{sex:"femal"}},{multi:true})

--or 
db.users.update({age:{$lte:23,$gte:21}},{$set:{sex:"femal"}},{multi:true});

 

 

参考doc:

Update Documents

Atomicity and Transactions

$isolated

$set

作者悦光阴
本文版权归作者和博客园所有,欢迎转载,但未经作者同意,必须保留此段声明,且在文章页面醒目位置显示原文连接,否则保留追究法律责任的权利。
分类: MongoDB





本文转自悦光阴博客园博客,原文链接:http://www.cnblogs.com/ljhdo/p/5792938.html,如需转载请自行联系原作者
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
4月前
|
NoSQL JavaScript 前端开发
如何使用 Node.js 连接和操作 MongoDB 数据库?
如何使用 Node.js 连接和操作 MongoDB 数据库?
221 2
|
3月前
|
NoSQL MongoDB Python
深入了解 Python MongoDB 操作:排序、删除、更新、结果限制全面解析
使用 sort() 方法对结果进行升序或降序排序。 sort() 方法接受一个参数用于“字段名”,一个参数用于“方向”(升序是默认方向)。
67 0
|
4天前
|
存储 JSON NoSQL
MongoDB的文档存储格式BSON和JSON的区别
MongoDB的文档存储格式BSON和JSON的区别
|
17天前
|
缓存 NoSQL 关系型数据库
【MongoDB】MongoDB更新操作时是否立刻fsync到磁盘?
【4月更文挑战第2天】【MongoDB】MongoDB更新操作时是否立刻fsync到磁盘?
|
18天前
|
消息中间件 NoSQL Kafka
云原生最佳实践系列 5:基于函数计算 FC 实现阿里云 Kafka 消息内容控制 MongoDB DML 操作
该方案描述了一个大数据ETL流程,其中阿里云Kafka消息根据内容触发函数计算(FC)函数,执行针对MongoDB的增、删、改操作。
|
2月前
|
SQL NoSQL Java
文档型数据库MongoDB
文档型数据库MongoDB
|
3月前
|
存储 JSON NoSQL
【MongoDB】<文档型数据库>Windows&Liunx安装MongoDB(无错完整)
【1月更文挑战第26天】【MongoDB】<文档型数据库>Windows&Liunx安装MongoDB(无错完整)
|
3月前
|
机器学习/深度学习 自然语言处理 NoSQL
|
3月前
|
存储 NoSQL MongoDB
Python小姿势 - Python操作MongoDB数据库
Python小姿势 - Python操作MongoDB数据库
|
4月前
|
NoSQL JavaScript 前端开发
MongoDB【CRUD练习-条件查询-文档关系】
MongoDB【CRUD练习-条件查询-文档关系】