Update the first occurrence of the data from a Mongodb database using Node.js


What do we intend to make ?

In this Chapter , we will Update the first occurrence of the data from a mongodb database using nodejs and updateOne() method of mongoDb.

Let's Start !

Step - 1 : Including Packages
We will start by requiring the package. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            


Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.

		        

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



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step - 3 : Update first Occurance
updateOne() is an inbuilt method of mongodb which is used to search the first occurance of the data and update it.

		        
//updateOne-mongodb-nodejs.js
//Update in mongodb
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 :

		        

D:\nj-learn-mongo>node updateOne-mongodb-nodejs.js

				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node updateone.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 occurances of data in mongoDb using nodejs as shown below:
		        
D:\nj-learn-mongo>node read-all-occurance-mongodb-nodejs.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. The reason being this method will update the whole entry. use the set operator to avoid other fields being left empty and to update specific fields.

$set


$Set operator is used to update the specific fields of a document in a mongodb collection. First let's print the contents of the database

		        
D:\nj-learn-mongo>node read-all-occurance-mongodb-nodejs.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.

		        
//updateOne-set-mongodb-nodejs.js
//Update in mongodb
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);
	});
});
					
	            

The output of the above code is :

		        
D:\nj-learn-mongo>node updateOne-set-mongodb-nodejs.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 we need to check the DB after the operation :
		        
D:\nj-learn-mongo>node read-all-occurance-mongodb-nodejs.js
Record Read successfully
Record Read successfully
[ { name: 'Nodejsera',
    age: '23',
    mobile: '9876543210',
    _id: 59706a56a4f6761e3cc22c98 },
  { _id: 59706c3771da112bd8b922dc,
    mobile: '1234567890',
    name: 'Rajatgarian' },
  { _id: 597073b2c6f60f5b3c23a1a5,
    website: 'nodejsera.com',
    phone: '1234567890' } ]
				
	            

In the above code only the name field is updated.