Update Methods

MongoDB provides the following methods for updating documents in a collection:

Method Description
 db.collection.updateOne()

Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.

New in version 3.2.

 db.collection.updateMany() 

Update all documents that match a specified filter.

New in version 3.2.

 db.collection.replaceOne()

Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter.

New in version 3.2.

 db.collection.update()

Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.

By default, the db.collection.update() method updates a single document. To update multiple documents, use the multi option.

These methods accept as parameters:

  • a filter document to determine which documents to update. These filters use the same syntax as read operations:

    • query filter document can specify equality condition with <field>:<value> expressions to select all documents that contain the <field> with the specified <value>:

      { <field1>: <value1>, ... }
    • query filter document can use the query operators to specify conditions in the following form:
      { <field1>: { <operator1>: <value1> }, ... }
  • an update document to specify the modification to perform or a replacement document that wholly replaces the matching documents except for the _id field, and
  • an options document.

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 db.collection.update()db.collection.updateOne()db.collection.updateMany(), or db.collection.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.

Example Collection

The examples on this page use the db.collection.find() method in the mongo shell. In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results.

To populate the users collection referenced in the examples, run the following in mongo shell:

NOTE: If the users collection already contains documents with the same _id values, you need to drop the collection (db.users.drop()) before inserting the example documents.

db.users.insertMany(
[
{
_id: 1,
name: "sue",
age: 19,
type: 1,
status: "P",
favorites: { artist: "Picasso", food: "pizza" },
finished: [ 17, 3 ],
badges: [ "blue", "black" ],
points: [
{ points: 85, bonus: 20 },
{ points: 85, bonus: 10 }
]
},
{
_id: 2,
name: "bob",
age: 42,
type: 1,
status: "A",
favorites: { artist: "Miro", food: "meringue" },
finished: [ 11, 25 ],
badges: [ "green" ],
points: [
{ points: 85, bonus: 20 },
{ points: 64, bonus: 12 }
]
},
{
_id: 3,
name: "ahn",
age: 22,
type: 2,
status: "A",
favorites: { artist: "Cassatt", food: "cake" },
finished: [ 6 ],
badges: [ "blue", "Picasso" ],
points: [
{ points: 81, bonus: 8 },
{ points: 55, bonus: 20 }
]
},
{
_id: 4,
name: "xi",
age: 34,
type: 2,
status: "D",
favorites: { artist: "Chagall", food: "chocolate" },
finished: [ 5, 11 ],
badges: [ "Picasso", "black" ],
points: [
{ points: 53, bonus: 15 },
{ points: 51, bonus: 15 }
]
},
{
_id: 5,
name: "xyz",
age: 23,
type: 2,
status: "D",
favorites: { artist: "Noguchi", food: "nougat" },
finished: [ 14, 6 ],
badges: [ "orange" ],
points: [
{ points: 71, bonus: 20 }
]
},
{
_id: 6,
name: "abc",
age: 43,
type: 1,
status: "A",
favorites: { food: "pizza", artist: "Picasso" },
finished: [ 18, 12 ],
badges: [ "black", "blue" ],
points: [
{ points: 78, bonus: 8 },
{ points: 57, bonus: 7 }
]
}
]
)

Update Specific Fields in a Document

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

To specify the modification to perform using update operators, use 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.

db.collection.updateOne()

New in version 3.2.

The following example uses the db.collection.updateOne() method on the users collection to update the first document that matches the filter favorites.artist equals "Picasso". The update operation:

  • uses the $set operator to update the value of the favorites.food field to "pie" and the value of the type field to 3,
  • 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.
db.users.updateOne(
{ "favorites.artist": "Picasso" },
{
$set: { "favorites.food": "pie", type: 3 },
$currentDate: { lastModified: true }
}
)

For more information and examples, see db.collection.updateOne().

db.collection.updateMany()

New in version 3.2.

The following example uses the db.collection.updateMany() method on the users collection to update all documents that matches the filter favorites.artist equals "Picasso". The update operation:

  • uses the $set operator to update the value of the favorites.artist field to "Pisanello" and the value of the type field to 3,
  • 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.
db.users.updateMany(
{ "favorites.artist": "Picasso" },
{
$set: { "favorites.artist": "Pisanello", type: 3 },
$currentDate: { lastModified: true }
}
)

For more information and examples, see db.collection.updateMany().

db.collection.update

The following example uses the db.collection.update() method on the users collection to update the first document that matches the filter favorites.artist equals "Pisanello". The update operation:

  • uses the $set operator to update the value of the favorites.food field to "pizza" and the value of the type field to 0,
  • 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.
db.users.update(
{ "favorites.artist": "Pisanello" },
{
$set: { "favorites.food": "pizza", type: 0, },
$currentDate: { lastModified: true }
}
)

To update multiple documents using the db.collection.update(), include the multi: true option:

db.users.update(
{ "favorites.artist": "Pisanello" },
{
$set: { "favorites.food": "pizza", type: 0, },
$currentDate: { lastModified: true }
},
{ multi: true }
)

Replace the 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() or db.collection.update(). When replacing a document, the replacement document must consist of only <field> : <value>.

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 _idfield, it must have the same value as the current value.

db.collection.replaceOne

The following example uses the db.collection.replaceOne() method on the users collection to replace the first document that matches the filter name equals "abc" with the new document:

db.users.replaceOne(
{ name: "abc" },
{ name: "amy", age: 34, type: 2, status: "P", favorites: { "artist": "Dali", food: "donuts" } }
)

db.collection.update

The following example uses the db.collection.update() method on the users collection to replace the first document that matches the filter name equals "xyz" with the new document:

db.users.update(
{ name: "xyz" },
{ name: "mee", age: 25, type: 1, status: "A", favorites: { "artist": "Matisse", food: "mango" } }
)

Additional Methods

The following methods can also update documents from a collection:

See the individual reference pages for the methods for more information and examples.

Write Acknowledgement

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

MongoDB - MongoDB CRUD Operations, Update Documents的更多相关文章

  1. MongoDB - MongoDB CRUD Operations, Insert Documents

    MongoDB provides the following methods for inserting documents into a collection: db.collection.inse ...

  2. MongoDB - MongoDB CRUD Operations, Delete Documents

    Delete Methods MongoDB provides the following methods to delete documents of a collection: Method De ...

  3. MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell

    The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...

  4. MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query

    By default, queries in MongoDB return all fields in matching documents. To limit the amount of data ...

  5. MongoDB - MongoDB CRUD Operations, Query Documents

    Query Method MongoDB provides the db.collection.find() method to read documents from a collection. T ...

  6. MongoDB - MongoDB CRUD Operations, Query Documents, Query for Null or Missing Fields

    Different query operators in MongoDB treat null values differently. The examples on this page use th ...

  7. MongoDB - MongoDB CRUD Operations

    CRUD operations create, read, update, and delete documents. Create Operations Create or insert opera ...

  8. MongoDB - MongoDB CRUD Operations, Bulk Write Operations

    Overview MongoDB provides clients the ability to perform write operations in bulk. Bulk write operat ...

  9. Mongodb系列- CRUD操作介绍

    ---恢复内容开始--- 一 Create 操作 在MongoDB中,插入操作的目标是一个集合. MongoDB中的所有写入操作在单个文档的层次上都是原子的. For examples, see In ...

随机推荐

  1. Java package

    Java中的一个包就是一个类库单元,包内包含有一组类,它们在单一的名称空间之下被组织在了一起.这个名称空间就是包名.可以使用import关键字来导入一个包.例如使用import java.util.* ...

  2. 技嘉主板+AMD CPU开启CPU虚拟化方法

    硬件环境:技嘉AB350+AMD Ryzen 5 1600X 由于安装虚拟机的需要,所以要开启CPU的虚拟化. 首先进入BIOS. 然后如图:(M.I.T-高级频率设定-CPU超频进阶设置-SVM M ...

  3. PXE Centos7和Centos6

    外网网卡:192.168.23.10, 内网网卡:192.168.10.2 PXE(preboot execute environment,预引导执行环境)是由Intel公司开发的最新技术,工作于Cl ...

  4. Beta阶段冲刺第一天

    提供当天站立式会议照片一张 讨论项目每个成员的昨天进展 昨天开始了Beta阶段的冲刺,总体讨论了一下这个阶段的任务,然后明确了个人分工. 讨论项目每个成员的存在问题 第一天暂时还没有什么问题,可能最大 ...

  5. react-自定义事件

    没有嵌套关系的组件(如兄弟组件)之间的通信,只能通过自定义事件的方式来进行. var EventEmitter = require('events').EventEmitter; import Rea ...

  6. 【Java】时间转json格式化

     @DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")     @JsonFormat(pattern="yyyy-MM-ddHH: ...

  7. 洛谷 P2421 A-B数对(增强版)

    题目描述 给出N 个从小到大排好序的整数,一个差值C,要求在这N个整数中找两个数A 和B,使得A-B=C,问这样的方案有多少种? 例如:N=5,C=2,5 个整数是:2 2 4 8 10.答案是3.具 ...

  8. P3386 【模板】二分图匹配

    题目背景 二分图 题目描述 给定一个二分图,结点个数分别为n,m,边数为e,求二分图最大匹配数 输入输出格式 输入格式: 第一行,n,m,e 第二至e+1行,每行两个正整数u,v,表示u,v有一条连边 ...

  9. 待续--mysql中key 、primary key 、unique key 与index区别

    mysql中key .primary key .unique key 与index区别

  10. QT uic rcc moc 命令行使用

    QT uic rcc moc 命令行使用 PS C:\Users\lsgx> uic.exe --help Usage: C:\Qt\Qt5.5.1\5.5\msvc2012\bin\uic.e ...