1.插入数据

db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
]);

2 更新语句$set

db.inventory.updateOne(
{item:"paper"},
{
$set:{"size.uom":"cm",status:"P"},
$currentDate:{lastModified:true} }
)

可以看到,如果没有的字段,则新增进去,同时修改了对应修改的内容

3 更新多条

db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)

4 替换

db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)

This page provides examples of how to update documents in using the following methods in the mongo shell:

  • db.collection.updateOne(<filter>, <update>, <options>)
  • db.collection.updateMany(<filter>, <update>, <options>)
  • db.collection.replaceOne(<filter>, <replacement>, <options>)

The examples on this page use the inventory collection. To create and/or populate the inventorycollection, run the following:

Copy
db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
]);

You can run the operation in the web shell below:

Update Documents in a Collection

To update a document, MongoDB provides update operators, such as $set, to modify field values.

To use the update operators, pass to the update methods an update document of the form:

{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

Update a Single Document

The following example uses the db.collection.updateOne() method on the inventory collection to update the first document where item equals "paper":

Copy
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)

The update operation:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of thestatus field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

Update Multiple Documents

New in version 3.2.

The following example uses the db.collection.updateMany() method on the inventory collection to update all documents where qty is less than 50:

Copy
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)

The update operation:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of thestatus field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

Replace a Document

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection that matches the filteritem equals "paper":

Copy
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)

Behavior

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.

_id Field

Once set, you cannot update the value of the _id field nor can you replace an existing document with a replacement document that has a different _id field value.

Document Size

When performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk.

Field Order

MongoDB preserves the order of the document fields following write operations except for the following cases:

  • The _id field is always the first field in the document.
  • Updates that include renaming of field names may result in the reordering of fields in the document.

Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the fields in a document.

Upsert Option

If updateOne()updateMany(), or replaceOne() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

[1] You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20. SeeWorking with the mongo Shell for more information.

15.Update Documents-官方文档摘录的更多相关文章

  1. Cocos Creator 加载和切换场景(官方文档摘录)

    Cocos Creator 加载和切换场景(官方文档摘录) 在 Cocos Creator 中,我们使用场景文件名( 可以不包含扩展名)来索引指代场景.并通过以下接口进行加载和切换操作: cc.dir ...

  2. ng的概念层次(官方文档摘录)

    官方文档是这么说的: You write Angular applications by: composing HTML templates with Angularized markup, writ ...

  3. Cocos Creator 使用计时器(官方文档摘录)

    在 Cocos Creator 中,我们为组件提供了方便的计时器,这个计时器源自于 Cocos2d-x 中的 cc.Scheduler,我们将它保留在了 Cocos Creator 中并适配了基于组件 ...

  4. Cocos Creator 生命周期回调(官方文档摘录)

    Cocos Creator 为组件脚本提供了生命周期的回调函数.用户通过定义特定的函数回调在特定的时期编写相关 脚本.目前提供给用户的声明周期回调函数有: onLoad start update la ...

  5. angular 模板语法(官方文档摘录)

    https://angular.cn/guide/template-syntax {{}} 和"" 如果嵌套,{{}}里面求完值,""就是原意 <h3&g ...

  6. Qt元类型(MetaType)注册入门(附一些官方文档的关键摘录)

    昨天调试项目时,突然发现如下消息: QObject::connect: Cannot queue arguments of type 'ERROR_LEVEL' (Make sure 'ERROR_L ...

  7. Sqoop 使用详解(内含对官方文档的解析)

    Sqoop 是 Cloudera 公司创造的一个数据同步工具,现在已经完全开源了. 目前已经是 hadoop 生态环境中数据迁移的首选,另外还有 ali 开发的 DataX 属于同类型工具,由于社区的 ...

  8. Spring Data Commons 官方文档学习

    Spring Data Commons 官方文档学习   -by LarryZeal Version 1.12.6.Release, 2017-07-27 为知笔记版本在这里,带格式. Table o ...

  9. Spring 4 官方文档学习(十一)Web MVC 框架

    介绍Spring Web MVC 框架 Spring Web MVC的特性 其他MVC实现的可插拔性 DispatcherServlet 在WebApplicationContext中的特殊的bean ...

  10. [翻译]PyMongo官方文档

    PyMongo官方文档翻译 周煦辰 2016-06-30 这是本人翻译的PyMongo官方文档.现在网上分(抄)享(袭)的PyMongo博客文章很多,一方面这些文章本就是抄袭的,谈不上什么格式美观,另 ...

随机推荐

  1. 基于jquery仿360网站图片选项卡切换代码

    今天给大家分享一款基于jquery仿360网站图片选项卡切换代码.这款实例适用浏览器:IE8.360.FireFox.Chrome.Safari.Opera.傲游.搜狗.世界之窗.效果图如下: 在线预 ...

  2. XML-RPC使用手册

    内容列表 Preface: About This Manual Introduction to XML-RPC for C/C++ What is XML-RPC? How Does XML-RPC ...

  3. JVM调优浅谈(转)

    1.数据类型 java虚拟机中,数据类型可以分为两类:基本类型和引用类型.基本类型的变量保存原始值,即:它代表的值就是数值本身,而引用类型的变量保存引用值.“引用值”代表了某个对象的引用,而不是对象本 ...

  4. 让 MySQL 支持 emoji 存储

    要让 MySQL 开启 utf8mb4 支持,需要一些额外的设置. 1. 检查 MySQL Server 版本 utf8mb4 支持需要 MySQL Server v5.5.3+ 2. 设置表的 CH ...

  5. 使用Javascript实现随机字符串

    方法一(其实是毫秒时间数字字符串): function randomString() { return '' + new Date().getTime(); } 方法二(随机字母数字字符串): var ...

  6. Generator生成器函数

    接触过Ajax请求的会遇到过异步调用的问题,为了保证调用顺序的正确性,一般我们会在回调函数中调用,也有用到一些新的解决方案如Promise相关的技术. 在异步编程中,还有一种常用的解决方案,它就是Ge ...

  7. List接口的实现类与ArrayList相似,区别是Vector是重量级的组件,使用使消耗的资源比较多

    List接口的实现类(Vector)(与ArrayList相似,区别是Vector是重量级的组件,使用使消耗的资源比较多.) 结论:在考虑并发的情况下用Vector(保证线程的安全). 在不考虑并发的 ...

  8. 要立刷金组flag了T_T

    刷了那么多银组,发现自己好多不会啊... 果然太弱 在这感谢hzwer神犇的blog.. 大部分题解都从黄学长这里来orz. orz.... 果然我太水

  9. RabbitMQ OS X下安装及常用命令-1

            RabbitMQ的主页在http://www.rabbitmq.com/ . 1. 安装Erlang RabbitMQ是用Erlang编写的,所以需要先安装Erlang,如果有的话跳过 ...

  10. sizeof 数组与指针

    在学习指针的时候,得到指针的定义和数组的定义一样,但是这时候就很好奇,指针只是一个地址,那数组和指针一样的话,sizeof时怎么得知其长度呢. 于是百度了下面的回复: 千万不要把数组名看成指针,尽管有 ...