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 documentconst 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,}如果替换操作无法与集合中的任何文档匹配,则不会进行任何更改。替换操作可以配置为执行更新或插入,尝试执行替换,但如果没有匹配的文档,则会插入具有指定字段和值的新文档。
您不能修改文档的_id字段,也不能将字段更改为违反唯一索引约束的值。 有关唯一索引的更多信息,请参阅 MongoDB Server 手册。
replaceOne() 示例:完整文件
注意
设置示例
该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。
以下代码是一个完整的独立运行文件,用于执行替换一操作:
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Create a query for documents where the title contains "The Cat from" const query = { title: { $regex: "The Cat from" } }; // Create the document that will replace the existing document const replacement = { title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, };
// Execute the replace operation const result = await movies.replaceOne(query, replacement); // Print the result console.log(`Modified ${result.modifiedCount} document(s)`); } finally { await client.close(); }}run().catch(console.dir);import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
interface Movie { title: string;}
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection<Movie>("movies");
const result = await movies.replaceOne( { title: { $regex: "The Cat from" } }, { title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, } ); console.log(`Modified ${result.modifiedCount} document(s)`); } finally { await client.close(); }}run().catch(console.dir);运行上述示例将产生以下输出:
Modified 1 document(s)API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: