Saturday, 28 November 2020

How to Insert an Array of documents in a collection using a JavaScript file in MongoDB? | MongoDB

🚀 Master MongoDB Batch Operations with Ram N Java!

Level up your backend skills and learn how to manage data like a pro! Subscribe now for high-quality, step-by-step tutorials designed to help you build faster and smarter.

🔔 SUBSCRIBE FOR FREE NOW

Inserting Multiple Documents Using JavaScript Files

Typing every insert command manually into the shell is fine for one or two records, but when you have a large dataset, you need a better strategy. In MongoDB, you can use JavaScript files to automate your data insertion, making the process cleaner, repeatable, and less error-prone!

Step 1: Create Your Data File

Create a file (e.g., data.js) and define an array of documents. Using the insertMany() method inside the script is the most efficient way to handle multiple records at once.

// data.js db.users.insertMany([   { "name": "Ram", "role": "Developer" },   { "name": "Shyam", "role": "Designer" },   { "name": "Gita", "role": "Manager" } ]);

Step 2: Execute the Script

Once your script is ready, you can load it into the MongoDB shell using the load() command. This executes the JavaScript code within the context of your current database connection.

load("path/to/your/data.js")

💡 Quick Beginner Tip

Using a JavaScript file for inserts is perfect for setting up initial seed data or testing environments. It allows you to keep your test data in version control and easily re-populate your database whenever you need a fresh start!

More MongoDB Mastery from Ram N Java:

No comments:

Post a Comment