Node.js + MongoDB Hello World Example

A simple node.js + MongoDB hello world example – how to connect, create database, collection and document, save, update, remove, get and display document (data).

First go and install
Node.js
MongoDB

1 – Installing MongoDB driver for node.js

Install MongoDB driver for your command line:

npm install mongodb

2 – Mongo Connection

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

var myCollection;
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
	if(err)
		throw err;
	console.log("connected to the mongoDB !");
	myCollection = db.collection('test_collection');
});

3 – Adding a document

In RDBMS a document is similar to an entry. A collection similar to a table.

	myCollection.insert({name: "doduck", description: "learn more than everyone"}, function(err, result) {
		if(err)
			throw err;

		console.log("entry saved");
	});

The content of our collection (table in RDBMS) just have one document (entry/row in RDBMS):
Our data entry is now:

{
“name”: “doduck”,
“description”: “learn more than everyone”
}

4 – Updating a document

We can now update our document. As Node.js is asynchrone make sure you run this command after the insert is finish and not in the same time (see full source code below)

	myCollection.update({name: "doduck"}, {name: "doduck", description: "prototype your idea"}, {w:1}, function(err) {
	if(err)
		throw err;
    	console.log('entry updated');
    });

Our data entry is now:

{
“name”: “doduck”,
“description”: “prototype your idea”
}

5 – Updating a document by adding a field

To add a field and update a document use the $set operation. If you don’t you will simply overwrite the full document.

	myCollection.update({name: "doduck"}, {$set: {industry: "France"}}, {w:1}, function(err) {
	if(err)
		throw err;
    	console.log('entry updated');
    });

Our data entry is now:

{
“name”: “doduck”,
“description”: “prototype your idea”,
“industry”: “France”
}

6 – Updating a document by adding a fields within a new field

MongoDB is a model free database who support field within field.

	myCollection.update({name: "doduck"}, {$set: {company: {employed: 10, officialName: "doduck LTD", industries: ["it consulting", "passionate programming"]}}}, {w:1}, function(err) {
		if(err)
			throw err;
    	console.log('entry updated');
    });

Our data entry is now:

{
“name” : “doduck”,
“description” : “prototype your idea”,
“industry” : “France”,
“company” : {
“employed” : 10,
“officialName” : “doduck LTD”,
“industries” : ["it consulting", "passionate programming"]
}
}

7 – finding a document

Looking at our data entry (see above) let’s find all our document where “name” is “doduck” and “company.officialName” is “doduck LTD”. In this example we should only find one entry.

	var cursor = myCollection.find({"name" : "doduck", "company.officialName" : "doduck LTD" });
	cursor.each(function(err, doc) {
		if(err)
			throw err;
		if(doc==null)
			return;

		console.log("document find:");
		console.log(doc.name);
		console.log(doc.company.employed);
	});

8 – Remove document

Remove our document matching “name” : “doduck”

	myCollection.findAndModify({name: "doduck"}, [], {remove:true}, function(err, object) {
		if(err)
			throw err;
		console.log("document deleted");
    });

9 – The full code source

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

var myCollection;
var db;

function removeDocument(onRemove){
	myCollection.findAndModify({name: "doduck"}, [], {remove:true}, function(err, object) {
		if(err)
			throw err;
		console.log("document deleted");
		onRemove();
    });
}

function findDocument(onFinded){
	var cursor = myCollection.find({"name" : "doduck", "company.officialName" : "doduck LTD" });
	cursor.each(function(err, doc) {
		if(err)
			throw err;
		if(doc==null)
			return;

		console.log("document find:");
		console.log(doc.name);
		console.log(doc.company.employed);
		onFinded();
	});
}

function fieldComplexeUpdateDocument(onUpdate){
	myCollection.update({name: "doduck"}, {$set: {company: {employed: 10, officialName: "doduck LTD", industries: ["it consulting", "passionate programming"]}}}, {w:1}, function(err) {
		if(err)
			throw err;
    	console.log('entry updated');
    	onUpdate();
    });
}

function fieldUpdateDocument(onUpdate){
	myCollection.update({name: "doduck"}, {$set: {industry: "France"}}, {w:1}, function(err) {
		if(err)
			throw err;
    	console.log('entry updated');
    	onUpdate();
    });
}

function simpleUpdateDocument(onUpdate){
	myCollection.update({name: "doduck"}, {name: "doduck", description: "prototype your idea"}, {w:1}, function(err) {
	if(err)
		throw err;
    	console.log('entry updated');
    	onUpdate();
    });
}

function addDocument(onAdded){
	myCollection.insert({name: "doduck", description: "learn more than everyone"}, function(err, result) {
		if(err)
			throw err;

		console.log("entry saved");
		onAdded();
	});
}

function createConnection(onCreate){

	MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
		if(err)
			throw err;
		console.log("connected to the mongoDB !");
		myCollection = db.collection('test_collection');

		onCreate();
	});
}

createConnection(function(){
	addDocument(function(){
		simpleUpdateDocument(function(){
			fieldUpdateDocument(function(){
				fieldComplexeUpdateDocument(function(){
					findDocument(function(){
						removeDocument(function(){
							console.log("The end");
						});
					});
				});
			});
		});
	});
});
  • http://www.matiasmenker.com Matias Menker

    Thanks man, great tutorial to start with this ejeje

  • Umut Hocaoglu

    Great tutorial, works flawlessly. I have a question though;

    I already have a dataset and some data in it and I’ve done the connection and findDocument() parts but I can’t seem to display it on localhost:8080

    Can you help me with this?

  • Umut Hocaoglu

    Woow, I don’t understand why you delete my question, plus I didn’t even say anything negative. A simple answer would suffice.

    • martin-magakian

      Sorry Umut Hocaoglu I never remove your answer. Actually I need to approuve it manually. That’s why you feel “it was deleted”
      Btw I didn’t understand your question. Did you solved it?

  • Klassy

    holy crap how are there no comments on this. This is the best mongodb help ive found anywhere. Thank you!!! Less talk, more show. I LOVE IT!

  • http://www.chrisbrocklesby.com/ Chris Brocklesby

    Brill post on MongoDB, Thank you ;)

  • Neel

    excellent article.really helpful

  • Haroon Ghawsi

    Great Job!

  • ajit

    thank you soo much

  • Jake Nort

    thanks!