Home » MongoDB

Update a document of a collection in MongoDB

In this article, we are going to update a document of collection name cars in MongoDB.
Submitted by Manu Jemini, on February 02, 2018

Here, in this example we are going to update a document through an Express server we need to full fill certain requirements:

  1. You must have MongoDB install: npm install MongoDB
  2. You must import, mongodb in the express server: var MongoDB = require('MongoDB ')
  3. You should always specify the url for MongoDB in accordance with your system: var url = "MongoDB ://localhost:27017/vehicle";

After fulfill the above three conditions, we should make connection to the database like this: MongoClient.connect(url, function(err,db){})

Then we have to make sure if there is any error or not with an if-else statement. If there is no error open a collection with its name: var collection = db.collection('cars');

Now in the example below we have to drop this collection by using the function drop: collection.update({"company_name":"nissan"},{$set: {"company_name":"BMW"}}, function(err,res){ })

Just like before we have to check for the error, if any. So to check if there is any error we use simple if-else statements.

The Object error will be passed by mongo itself and it will be false or null if there is no error, otherwise we will get an error object.

If we found an error we will console.log it, otherwise we will log the result of the query.

To make an optimum server to work smooth we should always close the connection after our use of it. There the last thing we do is close the db.


JS code:

// require MongoDB 
var MongoDB  = require('MongoDB ');
var MongoClient = MongoDB .MongoClient;
//create url
var url = "MongoDB ://localhost:27017/vehicle";
//connect with mongo client
MongoClient.connect(url, function(err,db){
		//console.log tthe connected url
		console.log('Connected to ',url);

		//get refernce of using collection
		var collection = db.collection('cars');

		// to update the documents

		collection.update({"company_name":"nissan"},{$set: {"company_name":"BMW"}}, function(err,res){
			// if updatation is being sucessful
			console.log('Update successful');


Output on console

MongoDB - Update a document 1

Output in shell (Before/After)

MongoDB - Update a document 2

MongoDB - Update a document 3



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.