Insert Documents in MongoDB using Node.js

Insert Documents in MongoDB using Node.js

Introduction 

In this program, we are going to learn how to insert multiple documents into a MongoDB database using Node.js.

MongoDB is a NoSQL database that stores data in the form of documents. A document is similar to an object in JavaScript. In this example, we will create a database named schoolDB and a collection named students.

We will insert a few student records into the students collection. Each student record contains details such as name, age, course, and city.

To do this, we will use the MongoDB driver for Node.js. The program will first connect to MongoDB, then select the database and collection, insert the documents, display the result, and finally close the database connection.

Procedure : Insert documents in MongoDB using Node.js

Step 1: Create a project folder and navigate to the folder

mkdir mongodb-node-insert
cd mongodb-node-insert

Step 2: Initialize Node.js project

npm init -y

Step 3: Install MongoDB driver

npm install mongodb

Step 4: Start MongoDB

Make sure MongoDB is running locally.

Default MongoDB URL:

mongodb://127.0.0.1:27017

Step 5: Create a file named with insertDocuments.js

Step 6: Write the Node.js program

Copy and Paste the following code in the insertDocuments.js file

const { MongoClient } = require("mongodb");

// MongoDB connection URL
const url = "mongodb://127.0.0.1:27017";

// Database name
const dbName = "schoolDB";

// Collection name
const collectionName = "students";

// Create MongoDB client
const client = new MongoClient(url);

async function insertDocuments() {
  try {
    // Connect to MongoDB
    await client.connect();
    console.log("Connected to MongoDB");

    // Select database
    const db = client.db(dbName);

    // Select collection
    const collection = db.collection(collectionName);

    // Documents to insert
    const students = [
      {
        name: "Rahul",
        age: 21,
        course: "Computer Science",
        city: "Delhi"
      },
      {
        name: "Priya",
        age: 22,
        course: "Information Technology",
        city: "Mumbai"
      },
      {
        name: "Aman",
        age: 20,
        course: "Electronics",
        city: "Bangalore"
      }
    ];

    // Insert multiple documents
    const result = await collection.insertMany(students);

    console.log(`${result.insertedCount} documents inserted successfully`);
    console.log(result.insertedIds);
  } catch (error) {
    console.error("Error inserting documents:", error);
  } finally {
    // Close connection
    await client.close();
    console.log("MongoDB connection closed");
  }
}

// Call the function
insertDocuments();

Step 7: Execute the program

node insertDocuments.js

Expected Output:

Connected to MongoDB
3 documents inserted successfully
MongoDB connection closed

Step 8: Check inserted data in MongoDB shell

mongosh
use schoolDB
db.students.find()

This will display the inserted student documents.

You can also open MongoDB Compass, if it is installed on your system, to verify that the schoolDB database, students collection, and the inserted documents have been created successfully.

Keywords:
MongoDB insert documents using Node.js, MongoDB Node.js tutorial, how to insert documents in MongoDB, Node.js MongoDB example, MongoDB CRUD operations, insertMany in MongoDB, MongoDB Compass tutorial, Node.js database tutorial, MongoDB beginner tutorial, MongoDB with JavaScript.

Previous Topic Student Registration App: MERN