Menu Docs
Página inicial do Docs
/ / /
Controlador Node.js
/ /

Insira vários documentos

Você pode inserir vários documentos usando o métodocollection.insertMany() . O insertMany() leva uma array de documentos a inserir na coleção especificada.

Você pode especificar mais opções no objeto options passado como o segundo parâmetro do método insertMany(). Especifique ordered:true para evitar a inserção dos documentos restantes se a inserção falhar em um documento anterior na array.

Especificar parâmetros incorretos para sua operação do insertMany() pode causar problemas. Tentar inserir um campo com um valor que viola regras de índice único resulta em um duplicate key error.

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 oGuia de 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("insertDB");
13 const foods = database.collection("foods");
14
15 // Create an array of documents to insert
16 const docs = [
17 { name: "cake", healthy: false },
18 { name: "lettuce", healthy: true },
19 { name: "donut", healthy: false }
20 ];
21
22 // Prevent additional documents from being inserted if one fails
23 const options = { ordered: true };
24
25 // Execute insert operation
26 const result = await foods.insertMany(docs, options);
27
28 // Print result
29 console.log(`${result.insertedCount} documents were inserted`);
30 } finally {
31 await client.close();
32 }
33}
34run().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 Food {
9 name: string;
10 healthy: boolean;
11}
12
13async function run() {
14 try {
15 const database = client.db("insertDB");
16 // Specifying a schema is optional, but it enables type hints on
17 // finds and inserts
18 const foods = database.collection<Food>("foods");
19
20 const result = await foods.insertMany(
21 [
22 { name: "cake", healthy: false },
23 { name: "lettuce", healthy: true },
24 { name: "donut", healthy: false },
25 ],
26 { ordered: true }
27 );
28 console.log(`${result.insertedCount} documents were inserted`);
29 } finally {
30 await client.close();
31 }
32}
33run().catch(console.dir);

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

3 documents were inserted

Voltar

Insira um documento