/

How to Insert Multiple Items at Once in a MongoDB Collection

How to Insert Multiple Items at Once in a MongoDB Collection

If you ever find yourself needing to insert multiple items at once in a MongoDB collection from a Node.js application, there’s a simple way to achieve this. Here’s how you can do it:

First, make sure you have the MongoDB driver for Node.js installed. You can do this by running the following command:

1
npm install mongodb

Once you have the MongoDB driver installed, you can then use the following code to insert multiple items at once:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const { MongoClient } = require('mongodb');

async function insertMultipleItems() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

try {
await client.connect();
const database = client.db('myapp');
const collection = database.collection('jobs');

const data = [{...}, {...}]; // Array of objects to be inserted

const result = await collection.insertMany(data); // Insert the array of objects

console.log(`${result.insertedCount} items inserted successfully.`);
} catch (err) {
console.error(err);
} finally {
client.close();
}
}

insertMultipleItems();

In this code, we create a MongoDB client and specify the connection URL for your MongoDB server. We then connect to the client and specify the database and collection we want to work with. Next, we define an array data with the objects that we want to insert.

Finally, we call insertMany() on the collection and pass in the data array to insert all the objects at once. The method returns a result object that contains information about the operation, such as the number of documents inserted.

Make sure to replace 'mongodb://localhost:27017' with the appropriate connection URL for your MongoDB server, and 'myapp' with the name of your database.

By following this approach, you can easily insert multiple items into a MongoDB collection from your Node.js application. Happy coding!

tags: [“MongoDB”, “Node.js”, “insertMany”, “database”]