Home » MongoDB

Map Reduce function in MongoDB

In this article, we are going to use map reduce function to sort out the result document in a particular format in MongoDB.
Submitted by Manu Jemini, on March 10, 2018

Map reduce is for data processing for large volumes of data into aggregated results. A record is a mongo document that is composed of field and value pairs. The documents are like JSON objects. Just like JSON in mongo we can put more documents inside a document.

To find a document in MongoDB through an Express server we need to full fill certain requirements:

Read more in previous article: How to use $gt in MongoDB?

In the example below, we have to the aggregated result.

    collection.mapReduce(map, reduce,{query:{id:"0001"},
    out:"result" },function(err,res){ });

Now, this function will return every document which matches that aggregate. 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.

 db.close();

JS file:

// 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){

	if(err)
	{
		console.log(err);
	}
	else
	{
		//console.log tthe connected url
		console.log('Connected to ',url);

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

		// to find the documents

		function map(){emit (this.id, this.qty)}
		function reduce(key,value) {return value.join()}

		collection.mapReduce(map, reduce,{query:{id:"0001"},out:"result" },function(err,res){
		if(err)
		{
			console.log(err);
		}
		else
		{
			//to console the response.
			console.log(res);
		}
		db.close();
		});
	}
});

Output in console:

Map reduce function in MongoDB



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.