How to Update a Document in MongoDB using NodeJS?
Last Updated :
03 Jun, 2024
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.
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.
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 = "GeeksforGeeks";
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:
Similar Reads
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Insta
1 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to Update Objects in a Document's Array in MongoDB?
In the area of MongoDB, managing a database with a large collection of documents can be challenging especially when it comes to updating specific objects within arrays of nested objects. This scenario is common in NoSQL databases like MongoDB. In this article, weâll explore some methods for updating
5 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
MongoDB - Update Single Document Using MongoShell
In MongoDB, you can update a single document in the collection using db.collection.updateOne() method. This method updates a document in the collection according to the filter. updateOne() is a mongo shell method, which can updates one document at a time. This method update the first document that s
4 min read
MongoDB - Update Multiple Documents Using MongoShell
In MongoDB, you can update multiple documents in the collection using db.collection.updateMany() method. This method updates all the documents in the collection that match the given filter. updateMany() is a mongo shell method, which can update multiple document. This method only accepts the documen
3 min read
How to push data in a MongoDB document ?
The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collectio
2 min read