MongoDB tutorial: how to update a document with Node.js

In this tutorial I will explain how to update a MongoDB document by using Node.js Framework. I hope you have seen my last tutorial about MongoDB.

First we need to connect to our MongoDB database:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://demouser:demouser@ds041851.mongolab.com:41851/database", function(err, db) {

 

});

Then, I will add a new document in my database:

var collection = db.collection('database');

var newdoc = {number:1,value:'first'}

collection.insert(newdoc,{w:1});

w:1 allows us to update or delete the added document.

Now, I will update my document:

var collection = db.collection('database');

collection.insert({number:1},{$set:{value:'second'}},{w:1});

In this way you can update your document!

I have also created a video tutorial where you can see how it works:









Leave a Comment