1 Sep 2013

Getting Started with MongoDB and mongojs

How to get started with MongoDB under node.js, using the mongojs module.

Install MongoDB:

$ sudo apt-get install mongodb

In most cases the Mongo daemon, mongod will be started automatically.

Use the Mongo shell to create and connect to a database named shop:

$ mongo shop
MongoDB shell version: 1.8.2
connecting to: shop

The database is created if it doesn't exist. We'll continue to use shop as our test database in future snippets and articles.

Insert some documents (similar to records, if you're completely new to MongoDB):

> db.products.insert({make:"Apple",model:"iPad"})
> db.products.insert({make:"Apple",model:"iPhone"})
> db.products.insert({make:"Samsung",model:"Galaxy Tab"})

Assert the products collection has been created:

> show collections

Select all the products to check they were inserted as expected:

> db.products.find()
{ "_id" : ObjectId("52235c518ba86adc7f08e6b0"), "make" : "Apple", "model" : "iPad" }
{ "_id" : ObjectId("52235c568ba86adc7f08e6b1"), "make" : "Apple", "model" : "iPhone" }
{ "_id" : ObjectId("52235c5d8ba86adc7f08e6b2"), "make" : "Samsung", "model" : "Galaxy Tab" }

Exit the Mongo shell:

> exit

Install mongojs, a node.js module which wraps the native mongodb-native module:

$ sudo npm install mongojs

Create and edit server.js:

var http = require("http");
var mongo = require("mongojs");

var db = mongo.connect("shop", ["products"]);

http.createServer(function(req, res) {

  db.products.find(function(err, products) {
    if(err) { throw err; }

    res.writeHead(200, {"Content-Type": "text/html"});

    products.forEach(function(product) {
      res.write("<td>" + product.make + "</td>");
      res.write("<td>" + product.model + "</td>");



A connection to the database is established. When a request is received the find method of the products collection is invoked and an array of product documents is provided to the callback function, which iterates and writes the details of each product to the response.

Start the node instance:

$ node server.js

Test in your browser:

SamsungGalaxy Tab