Overview
在本指南中,您可以学习;了解如何使用 Node.js驾驶员对MongoDB集合中的文档执行替换操作。替换操作的执行方式与更新操作不同。更新操作仅修改目标文档中的指定字段。替换操作会删除目标文档中的所有字段,然后替换为新字段。
替换文档
要执行替换操作,请创建替换文档,其中包含要在替换操作中使用的字段和值。 替换文档使用以下格式:
{ <field>: { <value> }, <field>: { ... } }
替换文档是要取代与查询筛选器匹配的现有文档的文档。
您可以使用可选的 options
参数指定更多选项,例如 upsert
。如果将 upsert
选项字段设立为 true
,则在没有文档与查询匹配的情况下,该方法将插入一个新文档。
如果在执行过程中发生错误,replaceOne()
方法会抛出异常。例如,如果您指定的值违反了唯一索引规则,replaceOne()
会抛出 duplicate key error
。
注意
如果您的应用程序在更新后需要该文档,请使用 集合.findOneAndReplace()方法,其接口与 replaceOne()
类似。您可以将 findOneAndReplace()
配置为返回原始匹配文档或替换文档。
例子
以 myDB.items
集合中的文档为例,其中包含描述待售商品、价格和可用数量的字段:
{ _id: 501, item: "3-wick beeswax candle", price: 18.99, quantity: 10, }
假设您想要将此文档替换为包含完全不同项目的描述的文档。您的替换操作可能如下所示:
const myDB = client.db("myDB"); const myColl = myDB.collection("items"); const filter = { _id: 501 }; // replace the matched document with the replacement document const replacementDocument = { item: "Vintage silver flatware set", price: 79.15, quantity: 1, }; const result = await myColl.replaceOne(filter, replacementDocument);
被替换文档包含替换文档的内容和不可变的 _id
字段,具体如下:
{ _id: 501, item: "Vintage silver flatware set", price: 79.15, quantity: 1, }
如果替换操作无法匹配集合中的任何文档,则不会进行任何更改。替换操作可以配置为执行更新或插入(upsert),尝试执行替换,但如果没有匹配的文档,则会插入具有指定字段和值的新文档。
您不能修改文档的_id
字段,也不能将字段更改为违反唯一索引约束的值。 有关唯一索引的更多信息,请参阅 MongoDB Server 手册。
replaceOne() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 sample_mflix
数据库中的 movies
集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下代码是一个完整的独立运行文件,用于执行替换一操作:
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a query for documents where the title contains "The Cat from" 16 const query = { title: { $regex: "The Cat from" } }; 17 18 // Create the document that will replace the existing document 19 const replacement = { 20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, 21 }; 22 23 // Execute the replace operation 24 const result = await movies.replaceOne(query, replacement); 25 26 // Print the result 27 console.log(`Modified ${result.modifiedCount} document(s)`); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 title: string; 10 } 11 12 async function run() { 13 try { 14 const database = client.db("sample_mflix"); 15 const movies = database.collection<Movie>("movies"); 16 17 const result = await movies.replaceOne( 18 { title: { $regex: "The Cat from" } }, 19 { 20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, 21 } 22 ); 23 console.log(`Modified ${result.modifiedCount} document(s)`); 24 } finally { 25 await client.close(); 26 } 27 } 28 run().catch(console.dir);
运行上述示例将产生以下输出:
Modified 1 document(s)
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: