Mongodb-node.js Tutorial Series

Update one operation in MongoDB using node.js

MongoDB-Nodejs tutorial | Perform mongodb operations using node.js



Overview

In this part of the mongodb operations using node.js tutorial series , we will learn about updating the first occurrence of data matching a certain criteria from a mongodb collection using node.js .

Let's Start !!
Step 1 - Include Package

We will start by including mongodb npm package as shown below :

												
var mongo = require('mongodb');
												
											

Step-2 : Establish Connection

Establish a connection between the mongoDb database and our node.js app using the following :

												
var new_db = "mongodb://localhost:27017/demo_db"
												
											

  • demo_db is the name of the database. You can change it in accordance with your database name.
  • 27017 is the port where mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step-3 : updateOne operation

updateOne() is an inbuilt method of mongodb which is used to update the first occurrence of data obtained using the search query.
The syntax of updateOne() function is given below :

										
db.collection("NAME_OF_THE_COLLECTION").updateOne(QUERY ,(CALLBACK_FUNCTION) => {});
										
									

An example is given below :

											
//update-one.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//Establishing a connection with the database
mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	//Query parameter is used to search the collection.
	var query = { name : "rishabhio" };
	//And When the query matches the data in the DB , "data" parameter is used to update the value.
	var data = { name : "nodejsera.com" , mobile : "1234567890" }
	//Accessing the collection using nodejs
	db.collection("details").updateOne(query , data, (err , collection) => {
		if(err) throw err;
		console.log("Record updated successfully");
		console.log(collection);
	});
});
											
										

You can run the above code using the following command :
											
>node update-one.js
Record updated successfully
{ result: { ok: 1, n: 1, nModified: 1 },
  connection: null,
  message: undefined,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1 }										
										

Now let's look at the details collection in the database Using the Read All occurrences operation as shown below:
										
>node read-all.js
Record Read successfully
[ { name: 'Nodejsera',
    age: '23',
    mobile: '9876543210',
    _id: 59706a56a4f6761e3cc22c98 },
  { _id: 59706c3771da112bd8b922dc,
    name: 'nodejsera.com',
    mobile: '1234567890' }, ]


										
									

We can observe that in the above output the age parameter is not there in the second entry because this method will update the whole entry and we didnot provide the age parameter in our query above, as a result it is removed. We can use the set operator to avoid other fields being left empty and to update specific fields.

$set parameter in update

$Set operator is used to update the specific fields of a document in a mongodb collection. let's print the contents of the database The syntax of updateOne() function is given below :

										
>node read-all.js
Record Read successfully
[ { name: 'Nodejsera',
    age: '23',
    mobile: '9876543210',
    _id: 59706a56a4f6761e3cc22c98 },
  { _id: 59706c3771da112bd8b922dc,
    name: 'nodejsera.com',
    mobile: '1234567890' },
  { _id: 597073b2c6f60f5b3c23a1a5,
    website: 'nodejsera.com',
    phone: '1234567890' } ]
										
									

Now lets perform the update operation to update the value of the entry where {"name" = "nodejsera.com"}.

											
//update-using-set.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"

mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	
	//Query parameter is used to search the collection.
	var query = { name : "nodejsera.com" };
	// set parameter is used to update only the name field of the entry and to keep the remaining fields same.
	var data = { $set : {name : "Rajatgarian" } }
	//Accessing COLLECTION IN MONGODB USING NODE.JS
	db.collection("details").updateOne(query , data, (err , collection) => {
		if(err) throw err;
		console.log("Record updated successfully");
		console.log(collection);
	});
});
											
										

You can run the above code using the following command :
											
>node update-using-set.js
Record updated successfully
{ 	result: { 
				ok: 1,
				n: 1, 
				nModified: 1 
			},
	connection: null,
	message: undefined,
	modifiedCount: 1,
	upsertedId: null,
	upsertedCount: 0,
	matchedCount: 1 
 }									
										

And also let's check the DB after the operation :
										
>node read-all.js
Record Read successfully
[ { name: 'Nodejsera',
    age: '23',
    mobile: '9876543210',
    _id: 59706a56a4f6761e3cc22c98 },
  { _id: 59706c3771da112bd8b922dc,
    mobile: '1234567890',
    name: 'Rajatgarian' },
  { _id: 597073b2c6f60f5b3c23a1a5,
    website: 'nodejsera.com',
    phone: '1234567890' } ]


										
									

We can observe that in the above output only the name field is updated.

What we learned

In this article we learned about

  1. Including monogdb npm package in your app.
  2. Establishing a connection between mongodb database and node.js application.
  3. updateOne() operation in mongodb using node.js
  4. $set parameter in mongodb update operation.