Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sangeetha SRank #212 · 11.4K reputationPosted Feb 20, 2025, 3:13 AM EST
To insert bulk data in MongoDB, you can use the
insertMany()method. Here’s a simple step-by-step guide:Prepare Your Data: Format your data as an array of documents (objects).
Connect to MongoDB: Ensure you have a connection to your MongoDB database.
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('your_mongo_connection_string'); try { await client.connect(); const database = client.db('your_database_name'); const collection = database.collection('your_collection_name'); \/\/ Insert bulk data const result = await collection.insertMany(bulkData); console.log(`${result.insertedCount} documents were inserted`); } finally { await client.close(); } } run().catch(console.dir);Run the Code: Execute your script, and the data will be inserted into the specified collection.
Emily FosterRank #3,495 · 415 reputationPosted Feb 20, 2025, 2:07 AM EST
Inserting bulk data in MongoDB can be a common requirement when dealing with large datasets or when importing data from various sources. MongoDB provides a feature called Bulk Write Operations which allows you to efficiently insert, update, or delete multiple documents in a single operation.
To insert bulk data in MongoDB, you can use the `insertMany()` or `bulkWrite()` methods depending on your specific requirements.
Here's a brief overview of how you can insert bulk data in MongoDB using these methods:
1. Using insertMany():
// Prepare an array of documents to insert in bulk const documents = [ { name: 'John', age: 30 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 } ]; // Insert the array of documents in bulk db.collection('yourCollection').insertMany(documents);2. Using bulkWrite():
// Prepare an array of write operations for bulkWrite const operations = [ { insertOne: { document: { name: 'John', age: 30 } } }, { insertOne: { document: { name: 'Alice', age: 25 } } }, { insertOne: { document: { name: 'Bob', age: 35 } } } ]; // Perform the bulkWrite operation db.collection('yourCollection').bulkWrite(operations);In both methods, you can provide an array of documents or operations to insert multiple documents at once, which can significantly improve the efficiency of inserting large amounts of data into MongoDB.
Keep in mind that while inserting bulk data can be efficient, you should also consider the impact on performance and resource utilization, especially when dealing with extremely large datasets.
I hope this explanation gives you a clear understanding of how to insert bulk data in MongoDB. If you have any more questions or need further assistance, feel free to ask!