Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Menu Docs
Página inicial do Docs
/ / /
Controlador Node.js
/ /

Substituir um documento

You can replace a single document using the collection.replaceOne() method. replaceOne() accepts a query document and a replacement document. If the query matches a document in the collection, it replaces the first document that matches the query with the provided replacement document. This operation removes all fields and values in the original document and replaces them with the fields and values in the replacement document. The value of the _id field remains the same unless you explicitly specify a new value for _id in the replacement document.

Você pode especificar mais opções, como upsert, usando o parâmetro opcional options. Se você definir o campo de opção upsert como true, o método inserirá um novo documento se nenhum documento corresponder à query.

O método replaceOne() lança uma exceção se ocorrer um erro durante a execução. Por exemplo, se você especificar um valor que viole uma regra de índice única, o replaceOne() lançará um duplicate key error.

Observação

Se o aplicação exigir o documento após a atualização, use o método collection.findOneAndReplace(), que possui uma interface semelhante replaceOne() a. Você pode configurar findOneAndReplace() o para gerar o documento correspondente original ou o documento de substituição.

Observação

Você pode utilizar este exemplo para se conectar a uma instância do MongoDB e interagir com um banco de dados que contém dados de amostra. Para saber mais sobre como se conectar à sua instância do MongoDB e carregar um conjunto de dados de amostra, consulte o guia Exemplos de uso.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async 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}
32run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10}
11
12async 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}
28run().catch(console.dir);

Ao executar o exemplo anterior, você vê a seguinte saída:

Modified 1 document(s)

Voltar

Modificar documentos