在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 文档的更新操作的更多相关文章

  1. 【三】MongoDB文档的CURD操作

    一.插入文档 使用insert方法插入文档到一个集合中,如果集合不存在创建集合,有以下几种方法: db.collection.insertOne({}):(v3.2 new)  #插入一个文档到集合中 ...

  2. es之对文档进行更新操作

    5.7.1:更新整个文档 ES中并不存在所谓的更新操作,而是用新文档替换旧文档: 在内部,Elasticsearch已经标记旧文档为删除并添加了一个完整的新文档并建立索引.旧版本文档不会立即消失 ,但 ...

  3. MongoDB 文档的删除操作

    在db中删除数据是十分危险的事,建议使用logic delete,即在doc中增加一个field:IsDeleted,将其设置为1,表示该doc在逻辑上被删除,这种workaround将delete操 ...

  4. mongoDB文档操作

    数据库操作无非就是增.删.改.查.这篇主要介绍增.删.改. 1.增 Mongodb插入操作很简单,使用关键字“insert”.实例: > db.test.blog.insert({"h ...

  5. MongoDB文档的增删改操作

    上一篇文章中介绍了MongoDB的一些基本知识,同时看到了怎么启动一个MongoDB服务,并且通过MongoDB自带的shell工具连接到了服务器. 这一次,就通过MongoDB shell介绍一下对 ...

  6. mongoDB 文档操作_删

    mongoDB 文档删除 MySQL对比 mysql delete from table where ... mongo db.collection.deleteOne(query) 删除函数 del ...

  7. MongoDB文档基本操作

    一.插入文档 使用insert()或save()方法向集合插入文档 >db.COLLECTION_NAME.insert(document) 详细用法可以参考MongoDB菜鸟教程 二.查找文档 ...

  8. MongoDB文档的基本操作

    1. MongoDB的安装方法 (1)下载MongoDB 相应的版本: (2)设置数据文件和日志文件的存放目录: (3)启动MongoDB服务: (4)将MongoDB作为服务启动. 2. Mongo ...

  9. mongodb文档的CRUD

    本章会介绍对数据库移入或者移出数据的基本操作 向集合添加文档 从集合删除文档 更新现有的文档 为这些操作选择合适的安全级别 添加删除数据库 添加数据库 :use foo  如果存在foo 就use   ...

随机推荐

  1. POJ2104 K-th Number(主席树)

    题目 Source http://poj.org/problem?id=2104 Description You are working for Macrohard company in data s ...

  2. React 组件性能优化

    React组件性能优化 前言 众所周知,浏览器的重绘和重排版(reflows & repaints)(DOM操作都会引起)才是导致网页性能问题的关键.而React虚拟DOM的目的就是为了减少浏 ...

  3. CODEVS 天梯 代码记录

    所有水题均被折叠 Lv.1 青铜 1201 #include<iostream> #include<cstring> #include<algorithm> #in ...

  4. 转:界面之下:还原真实的 MVC、MVP、MVVM 模式

    前言 做客户端开发.前端开发对MVC.MVP.MVVM这些名词不了解也应该大致听过,都是为了解决图形界面应用程序复杂性管理问题而产生的应用架构模式.网上很多文章关于这方面的讨论比较杂乱,各种MV*模式 ...

  5. Ajax完整篇(转载)

    Ajax 完整教程 第 1 页 Ajax 简介Ajax 由 HTML.JavaScript™ 技术.DHTML 和 DOM 组成,这一杰出的方法可以将笨拙的 Web 界面转化成交互性的 Ajax 应用 ...

  6. Daily Scrum02 12.17

    软件发布到了最后的阶段,大家都在抓紧时间DEBUG,美化界面,做各种测试…… 大家抓紧最后一把劲,一起努力冲最后一下,努力吧! Member 任务进度 下一步工作 吴文会 会议组织 会议总结,发表博客 ...

  7. Metaio在Unity3D中报错 Start: failed to load tracking configuration: TrackingConfigGenerated.xml 解决方法

    报错:Start: failed to load tracking configuration: TrackingConfigGenerated.xml Start: failed to load t ...

  8. js中的caller和callee属性

    caller返回一个对函数的引用,该函数调用了当前函数. functionName.caller functionName 对象是所执行函数的名称. 说明对于函数来说,caller 属性只有在函数执行 ...

  9. Think in 递归

    网上写递归的文章可以用汗牛充栋来形容了,大多数都非常清晰而又细致的角度上讲解了递归的概念,原理等等.以前学生的时候,递归可以说一直是我的某种死穴,原理,细节我都懂,但是不管是在如何运用或者如何试试算法 ...

  10. WebView解析

    WebView解析   WebView是一个基于Webkit的,相当于内置浏览器的强大功能的组件,WebView的使用这么分四步说明:添加组件,加载资源,属性设置,辅助功能. 一.WebView的添加 ...