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.

Reading Documents from MongoDB using Node.js

In the previous section, we inserted student documents into the students collection. Now, let us learn how to read those documents from MongoDB using Node.js.

We will use the find() method to fetch documents from the collection and display them in the console.

Step-by-step procedure to read documents 

Step 1: Create a new file

Create a file named:

readDocuments.js

Step 2: Write the Node.js program

Copy and Paste the following code in the readDocuments.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 readDocuments() {
  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);

    // Read all documents
    const students = await collection.find({}).toArray();

    // Display documents
    console.log("Student Documents:");
    console.log(students);

  } catch (error) {
    console.error("Error reading documents:", error);
  } finally {
    // Close MongoDB connection
    await client.close();
    console.log("MongoDB connection closed");
  }
}

// Call function
readDocuments();

Step 3: Run the program

node readDocuments.js
Expected Output:

Connected to MongoDB

Student Documents:
[
  {
    _id: ObjectId("..."),
    name: "Rahul",
    age: 21,
    course: "Computer Science",
    city: "Delhi"
  },
  {
    _id: ObjectId("..."),
    name: "Priya",
    age: 22,
    course: "Information Technology",
    city: "Mumbai"
  }
]

MongoDB connection closed

You can also open MongoDB Compass, if it is installed on your system, to verify the documents inside the students collection.

Keywords:
MongoDB insert documents using Node.js, MongoDB read documents using Node.js, MongoDB Node.js tutorial, how to insert documents in MongoDB, how to read documents in MongoDB, Node.js MongoDB example, MongoDB CRUD operations, insertMany in MongoDB, find method in MongoDB, MongoDB Compass tutorial, Node.js database tutorial, MongoDB beginner tutorial, MongoDB with JavaScript, MongoDB find() example, reading data from MongoDB using Node.js, MongoDB collection tutorial, Node.js MongoDB CRUD example.

Previous Topic Student Registration App: MERN Next Topic fit_transform and transform