Steps to Update Document in MongoDB

Initially set up a Nodejs Project using the following command.

npm init 
or
npm init -y
  • npm init command asks some setup questions which are important for the project
  • npm init -y command is used to set all the answers of the setup questions as yes.

Install the MongoDB package

npm install mongodb

You can verify the installation using following command in the integrated terminal of IDE.

mongodb --version

NodeJS and MongoDB Connection

Once the MongoDB is installed we can use MongoDB database with the Nodejs Project.Initially we need to specify the database name ,connection URL and the instance of MongoDBClient.

const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

const dbName = 'project_name'; // Database Name

async function main() {

await client.connect(); // Use connect method to connect to the server
console.log('Connected successfully to server');

const db = client.db(dbName);
const collection = db.collection('collection_name');

//Can Add the CRUD operations
}

main() .then(console.log)
.catch(console.error)
.finally(() => client.close());

Creating a Collection in MongoDB

In this operation we create a collection inside a database.Intilally we specify the database in which collections is to be created.

const dbName = 'database_name';                          //Sepcify Database

await client.connect(); //Connect to db

const collection = db.collection('collection_name'); //Create Collection

const doc_array = [
{document1 },
{document2 },
{ document3 },
];
const insertDoc = await collection.insertMany( doc_array ); //Insert into collection
console.log('Inserted documents =>', insertDoc);

Add the above code in the main() function as mentioned above

  • doc_array contains the three documents
  • Documents are inserted into the collection using the insertMany() function.

Read Operation

We can read the documents inside the collection using the find() method.

const doc = await collection.find({}).toArray();
console.log('Found documents =>', doc );
  • find() method is used to along with empty {} are used to read all the documents in the collection.Which are further converted into the array using the toArray() method.

Update Operation

To update the documents we can use updateOne() or updateMany methods.

Syntax of update() method

db.collection_name.update(   query,    update,    optional)
  • query is used to filter out the documents which are to be updated
  • update is to update the values of the fields int the document.
  • optional parameter contains the upsert ,multi, writeConcern, collation, arrayFilters field which are use according to conditions
const updateDoc = await collection.updateOne(  conditon  ,  field to update       );
console.log('Updated documents =>', updateDoc);

Example:

JavaScript
const PORT = 8000;
const { MongoClient } = require("mongodb");
const url = "mongodb://127.0.0.1:27017";
const dbName = "w3wiki";

const studentsData = [
    { rollno: 101, Name: "Raj ", favSub: "Math" },
    { rollno: 102, Name: "Yash", favSub: "Science" },
    { rollno: 103, Name: "Jay", favSub: "History" },
];
// Connection
MongoClient.connect(url)
    .then(async (client) => {
        console.log("Connected successfully to MongoDB");

        const db = client.db(dbName);
        const collection = db.collection("students");

        try {
            // Add students to the database
            await collection.insertMany(studentsData);
            console.log("Three students added successfully");

            // Query all students from the database
            const students = await collection.find().toArray();
            console.log("All students:", students);

            const updateResult = await collection.updateOne(
                { rollno: 103 },
                { $set: { favSub: "Geography" } }
            );
            const students1 = await collection.find().toArray();
            console.log("After Update :", students1);
        } catch (err) {
            console.error("Error :", err);
        } finally {
            // Close the connection when done
            client.close();
        }
    })
    .catch((err) => {
        console.error("Error connecting to MongoDB:", err);
    });

Output:



How to Update a Document in MongoDB using NodeJS?

Updating documents in MongoDB is a basic operation for maintaining and managing your database effectively. Node.js, combined with MongoDB, offers a powerful and flexible environment for performing database operations.

In this article we will learn how to update a document from a MongoDB collection, starting from connecting the MongoDB to NodeJS, creating a collection and inserting the documents inside it.

Similar Reads

Update Document in MongoDB using Node.js

MongoDB Stores data in BSON format in the documents. Documents are similar to rows in SQL Table. A collection can contain any number of documents. Each document in a collection has an auto-generated unique ID named ” _id”. We can update the documents in the collection using the ID or using any other condition. updateOne() function or updateMany() can be used to update the documents in the MongoDB....

Steps to Update Document in MongoDB

Initially set up a Nodejs Project using the following command....