Performing a simple find/select in MongoDB from node.js

Here’s a quick tip for those of you interested in using MongoDB from a node.js application.  Here we provide an example of how to perform a “find” to retrieve documents from a MongoDB collection.  For those of you used to the SQL world, this would be equivalent to a SELECT.  The following code snippet retrieves all documents in the “users” collection which have a field “age” with a value greater than 30… or in simple terms, retrieve all users who are older than 30.

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

// Call our 'run_query' function to find all documents in the
// 'users' collection with a field 'age' greater than 30.
run_query('users', { 'age' : { '$gt' : 30 }});

// Function used to connect to the MongoDB database
function connect_database(next) {
	var db_cli = new MongoClient();

	var connection_result = function(err,db) {
		if(!err) {
			// Call the callback with the new DB object
			next(null,db);
		} else {
			console.log("DB connection failed. Details: " 
						+ err.message);
			next(err);
		}
	};

	// Specify the URL which contains the host and database
	// You would also specify username/password in this URL 
	// In this case "localhost" as the host and "test" as the DB
	var mongo_url = "mongodb://localhost/test";

	db_cli.connect(mongo_url,connection_result);
};

// Function used to get a collection object
function connect_collection(db, collection_name,next_step) {
    var col_connected = function(err,collection) {
        if(!err) {
            next_step(null, collection);
        } else {
            console.log("Failed to connect collection. Details: " 
						+ err.message);
            next_step(new Error("Failed to connect collection: " 
						+ err.message));
        }
    };

	// Get a specific collection object from the database
    db.collection(collection_name,col_connected);
};

// Function used to connect to the database, select a collection,
// run the query, and output the results to the console.
function run_query(collection_name, query_object) {
	var database;

	// Called for each document in the collection
	var each_document = function(err, doc) {
		if(!err) {
			// The mongo driver calls this function with a null
			// document to indicate the end of all the records
			// so we check if we've reached the last document
			if(doc) {
				console.log("Result:");
				console.dir(doc);
				console.log("------------------");
			} else {
				// Close our database connection
				database.close();
			}
		} else {
			console.log("Error getting document. " + err.message);
		}
	};

	// Result after executing "find"
	var receive_cursor = function(err, cursor) {
        if(!err) {
			console.log("------------------");
			// Call the "each" function to specify that the 
			// "each_document" function should be called for
			// every document in the result set
            cursor.each(each_document);
        } else {
            console.log("Error reading database results. " 
						+ err.message);
        }
    };

	// Result from collection object request
	var col_connected = function(err, collection) {
		if(!err) {
			// Call the "find" function of the collection object
			// which performs a query and returns the cursor
			// to the "receive_cursor" function
			collection.find(query_object,receive_cursor);
		}
	}

	// Result from database connection request
	var db_connected = function(err,db) {
		if(!err) {
			database = db;
			// Connect the collection we are using
			connect_collection(database, collection_name, 
                      col_connected);
		}
	}

	// Connect to the database
	connect_database(db_connected);
}

The steps involved are documented in the code itself, so have a read through to see how it is working.  This is working code, so if you want to test it yourself, you’ll just need to manually create a test database and run the following using the Mongo client (this is in the mongo command line client, not in node.js).

db.createCollection('users');

db.users.insert({ first_name: 'Bob', last_name : 'Smith', age: 52 });

db.users.insert({ first_name: 'Angela', last_name : 'Finch', age: 23 });

db.users.insert({ first_name: 'Bart', last_name : 'Simpson', age: 12 });

db.users.insert({ first_name: 'Homer', last_name : 'Simpson', age: 35 });

Now that you have some data, if you run the example above in node.js, you should get this as output on the command-line.

------------------
Result:
{ _id: 520651e37815d17648b5a249,
  first_name: 'Bob',
  last_name: 'Smith',
  age: 52 }
------------------
Result:
{ _id: 5206523a7815d17648b5a24c,
  first_name: 'Homer',
  last_name: 'Simpson',
  age: 35 }
------------------

As you can see, the query returned the two user records who are older than 30.

That’s it for a simple find operation in MongoDB using node.js.  If you have any questions/comments, please feel free to leave them below.

1 thought on “Performing a simple find/select in MongoDB from node.js”

  1. Hello! What should I do if I want to store the retrieved data in a variable that can be accessed by an ordinary JavaScript module, so I can manipulate the data and have it formatted in HTML?

Leave a Comment