Node.js Tutorial

Node.js MongoDB Insert Record

Node.js MongoDB Insert Record
Node.js MongoDB Insert Record

Node.js MongoDB Insert Record

When working with Node.js and MongoDB, inserting data into a collection is one of the most common database operations. MongoDB provides methods such as insertOne() and insertMany() to insert single or multiple documents efficiently.

In this tutorial, you will learn how to insert a single record and insert multiple records into MongoDB using Node.js with practical examples.

Node.js MongoDB Insert Record

Insert a Single Record in MongoDB

The insertOne() method is used to insert a single document into a MongoDB collection. It accepts a JavaScript object containing the fields and values that you want to store.

Example: Insert a single record into the “employees” collection

Create a JavaScript file named insert.js and add the following code:

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

const url = "mongodb://localhost:27017";
const client = new MongoClient(url);

async function insertRecord() {
    try {
        await client.connect();

        const db = client.db("MongoDatabase");
        const employees = db.collection("employees");

        const employee = {
            name: "Ajeet Kumar",
            age: 28,
            address: "Delhi"
        };

        const result = await employees.insertOne(employee);

        console.log("1 record inserted");
        console.log("Inserted ID:", result.insertedId);
    } catch (error) {
        console.error(error);
    } finally {
        await client.close();
    }
}

insertRecord();

Now open your terminal and run the following command:

node insert.js

You will see a message similar to 1 record inserted in the console. The returned insertedId confirms the unique ID generated for the newly inserted document.

Introduction to Applied AI:

Insert Multiple Records in MongoDB

MongoDB also allows you to insert multiple documents at once using the insertMany() method. This method accepts an array of JavaScript objects, with each object representing a document.

YT:- DecodeIT

Example: Insert multiple records into the “employees” collection

Create another JavaScript file named insertall.js and add the following code:

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

const url = "mongodb://localhost:27017";
const client = new MongoClient(url);

async function insertMultipleRecords() {
    try {
        await client.connect();

        const db = client.db("MongoDatabase");
        const employees = db.collection("employees");

        const employeeRecords = [
            {
                name: "Mahesh Sharma",
                age: 25,
                address: "Ghaziabad"
            },
            {
                name: "Tom Moody",
                age: 31,
                address: "CA"
            },
            {
                name: "Zahira Wasim",
                age: 19,
                address: "Islamabad"
            },
            {
                name: "Juck Ross",
                age: 45,
                address: "London"
            }
        ];

        const result = await employees.insertMany(employeeRecords);

        console.log(
            "Number of records inserted: " + result.insertedCount
        );
    } catch (error) {
        console.error(error);
    } finally {
        await client.close();
    }
}

insertMultipleRecords();

Run the script using the following command:

node insertall.js

After running the command, the console will display the number of documents that were successfully inserted into the employees collection.

YT:- DecodeIT

insertOne() vs insertMany() in MongoDB

MethodPurposeInput
insertOne()Inserts a single documentOne JavaScript object
insertMany()Inserts multiple documentsAn array of JavaScript objects

How to Insert Data in MongoDB Using Node.js

To insert data into MongoDB using Node.js, you generally need to connect your application to MongoDB, select the required database and collection, create the document or documents, and then use insertOne() or insertMany().

For a single document, use insertOne(). When you need to add several documents in one operation, insertMany() is the better choice.

Conclusion

In this tutorial, we learned how to insert records into MongoDB using Node.js. The insertOne() method is useful for adding a single document, while insertMany() can be used to add multiple documents efficiently.

These methods are commonly used when building Node.js MongoDB CRUD applications, REST APIs, and database-driven projects.

Keywords: Node.js MongoDB insert record, MongoDB insertOne example, MongoDB insertMany Node.js, how to insert data in MongoDB using Node.js, Node.js MongoDB insert data, insert data MongoDB Node.js, MongoDB Node.js CRUD, Node.js MongoDB API, bulk insert MongoDB Node.js, Node.js Express MongoDB CRUD node js mongodb insert record example
node js mongodb insert record w3schools
how to insert data in mongodb using node js using mongoose
node js mongodb insert record github
node js mongodb insert record json
node js mongodb example
mongodb insertone
mongodb atlas

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us