Overview
您可以使用更新和替换操作来修改 MongoDB 集合中的文档。更新操作可以修改文档的字段和值,同时保持其他字段和值不变。替换操作使用指定字段和值替换现有文档中的所有字段和值,同时保持 _id
字段值不变。
Node.js 驱动程序提供以下用于更改文档的方法:
updateOne()
updateMany()
replaceOne()
要学习;了解如何替换文档,请参阅 替换文档指南。
提示
互动实验室
本页包括一个简短的交互式实验室,演示了如何使用 updateMany()
方法修改数据。无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。
若要启动实验室,请单击页面顶部的“Open Interactive Tutorial”按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 (⛶)。
Update Documents
如需对一个或多个文档执行更新,请创建更新文档,指定更新操作符(要执行的更新类型)以及描述更改的字段和值。更新文档使用以下格式:
{ <update operator>: { <field> : { ... }, <field> : { } }, <update operator>: { ... } }
更新文档的顶层包含以下一个或多个更新运算符:
$set
:用指定值替换字段的值$inc
:递增或递减字段值$rename
:重命名字段$unset
:删除字段$mul
:将字段值乘以指定的数值
有关更新操作符及其用法的完整列表,请参阅 MongoDB Server 手册。
更新操作符只适用于更新文档中与之关联的字段。
注意
更新操作中的聚合管道
如果您使用的是 MongoDB 4.2或更高版本,则可以在更新操作中使用由聚合阶段子集组成的聚合管道。 有关 MongoDB 在更新操作中使用的聚合管道中支持的聚合阶段的更多信息,请参阅有关使用聚合管道构建更新的教程。
例子
以 myDB.items
集合中的文档为例,其中包含描述待售商品、价格和可用数量的字段:
{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 7, }
如果应用 $set
更新运算符,并为 quantity
添加新值,则可以使用以下更新文档:
const myDB = client.db("myDB"); const myColl = myDB.collection("items"); const filter = { _id: 465 }; // update the value of the 'quantity' field to 5 const updateDocument = { $set: { quantity: 5, }, }; const result = await myColl.updateOne(filter, updateDocument);
更新后的文档类似以下内容,其中 quantity
字段的值已更新,而所有其他值则保持不变:
{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 5, }
如果更新操作无法与集合中的任何文档匹配,则不会进行任何更改。更新操作可以配置为执行更新或插入,尝试执行更新,但如果没有匹配的文档,则会插入具有指定字段和值的新文档。
您不能修改文档的_id
字段,也不能将字段更改为违反唯一索引约束的值。 有关唯一索引的更多信息,请参阅 MongoDB Server 手册。
updateOne() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
此示例使用 $set
更新操作符符指定文档字段的更新值。有关更新操作符的更多信息,请参阅MongoDB更新操作符参考文档。
以下代码是一个完整的独立运行文件,用于执行更新一个操作:
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a filter for movies with the title "Random Harvest" 16 const filter = { title: "Random Harvest" }; 17 18 /* Set the upsert option to insert a document if no documents match 19 the filter */ 20 const options = { upsert: true }; 21 22 // Specify the update to set a value for the plot field 23 const updateDoc = { 24 $set: { 25 plot: `A harvest of random numbers, such as: ${Math.random()}` 26 }, 27 }; 28 29 // Update the first document that matches the filter 30 const result = await movies.updateOne(filter, updateDoc, options); 31 32 // Print the number of matching and modified documents 33 console.log( 34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, 35 ); 36 } finally { 37 // Close the connection after the operation completes 38 await client.close(); 39 } 40 } 41 // Run the program and print any thrown errors 42 run().catch(console.dir);
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 // Define the Movie interface 11 interface Movie { 12 plot: string; 13 title: string; 14 } 15 16 async function run() { 17 try { 18 const database = client.db("sample_mflix"); 19 const movies = database.collection<Movie>("movies"); 20 21 /* Update a document that has the title "Random Harvest" to have a 22 plot field with the specified value */ 23 const result = await movies.updateOne( 24 { title: "Random Harvest" }, 25 { 26 $set: { 27 plot: `A harvest of random numbers, such as: ${Math.random()}`, 28 }, 29 }, 30 /* Set the upsert option to insert a document if no documents 31 match the filter */ 32 { upsert: true } 33 ); 34 35 // Print the number of matching and modified documents 36 console.log( 37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)` 38 ); 39 } finally { 40 // Close the connection after the operation completes 41 await client.close(); 42 } 43 } 44 // Run the program and print any thrown errors 45 run().catch(console.dir);
运行上述示例将产生以下输出:
1 document(s) matched the filter, updated 1 document(s)
updateMany() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下代码是一个完整的独立运行文件,用于执行更新多次操作:
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "movies" collection in the "sample_mflix" database 13 const database = client.db("sample_mflix"); 14 const movies = database.collection("movies"); 15 16 // Create a filter to update all movies with a 'G' rating 17 const filter = { rated: "G" }; 18 19 // Create an update document specifying the change to make 20 const updateDoc = { 21 $set: { 22 random_review: `After viewing I am ${ 23 100 * Math.random() 24 }% more satisfied with life.`, 25 }, 26 }; 27 // Update the documents that match the specified filter 28 const result = await movies.updateMany(filter, updateDoc); 29 console.log(`Updated ${result.modifiedCount} documents`); 30 } finally { 31 // Close the database connection on completion or error 32 await client.close(); 33 } 34 } 35 run().catch(console.dir);
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 enum Rating { 11 G = "G", 12 PG = "PG", 13 PG_13 = "PG-13", 14 R = "R", 15 NR = "NOT RATED", 16 } 17 18 // Create a Movie interface 19 interface Movie { 20 rated: Rating; 21 random_review?: string; 22 } 23 24 async function run() { 25 try { 26 // Get the "movies" collection in the "sample_mflix" database 27 const database = client.db("sample_mflix"); 28 const movies = database.collection<Movie>("movies"); 29 30 // Update all documents that match the specified filter 31 const result = await movies.updateMany( 32 { rated: Rating.G }, 33 { 34 $set: { 35 random_review: `After viewing I am ${ 36 100 * Math.random() 37 }% more satisfied with life.`, 38 }, 39 } 40 ); 41 console.log(`Updated ${result.modifiedCount} documents`); 42 } finally { 43 // Close the database connection on completion or error 44 await client.close(); 45 } 46 } 47 run().catch(console.dir);
运行前面的示例,您会看到如下输出:
Updated 477 documents
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: