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 | const { MongoClient } = require('mongodb'); |
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”]