首页 > 代码库 > 使用MongoVUE对MongoDB 进行MapReduce操作步骤

使用MongoVUE对MongoDB 进行MapReduce操作步骤

Step 1

Open MongoVUE and connect to the server that contains the collection “cities”

Connect to MongoDB

 

Step 2

Right-click on “cities” collection under “Database Explorer”, and select “MapReduce”. This will launch the MapReduce view.

Launch the MapReduce view

 

Step 3

Write the JavaScript code for Map function in “Map” tab.

Write Map code

 

Step 4

Go to “Reduce” tab and enter your JavaScript Reduce code.

Write Reduce code

 

Step 5

Go to “Finalize” tab and enter your JavaScript Finalize code.

Write Finalize code

 

Step 6

Go to “In & Out” tab. Enter the Json code under “{Query}” to exclude cities from USA.

Enter Input options under {Query}

 

Step 7

We are almost done, but before we run this program, let’s just save it to disk first. Click on the small arrow next to “Go!” button and select “Save As”. You will be prompted for a filename. Enter a suitable name, and your MapReduce code will be saved to a corresponding “.vumr” file on your computer.

image

 

Step 8

We are ready to roll. Just click the “Go!” button, and that’ll start the MapReduce operation. At the end, you’ll see the results in the bottom pane. You can also check the time taken in the statusbar. Additionally, the shell command is also available under “Learn Shell” toolbox.

MapReduce is done

 

This completes our tutorial. You can check the Learn Shell toolbox, it displays the following command.

 

db.runCommand({ mapreduce: cities,
 map : function Map() {
	var key = this.CountryID;
	emit(key, {
		"data":
		[
			{
				"name" : this.City,
				"lat"  : this.Latitude,
				"lon"  : this.Longitude
			}
		]
	});
}
 reduce : function Reduce(key, values) {

	var reduced = {"data":[]};
	for (var i in values) {
		var inter = values[i];
		for (var j in inter.data) {
			reduced.data.push(inter.data[j]);
		}
	}

	return reduced;
}

 finalize : function Finalize(key, reduced) {

	if (reduced.data.length == 1) {
		return { "message" : "This Country contains only 1 City" };
	}

	var min_dist = 999999999999;
	var city1 = { "name": "" };
	var city2 = { "name": "" };

	var c1;
	var c2;
	var d;
	for (var i in reduced.data) {
		for (var j in reduced.data) {
			if (i>=j) continue;
			c1 = reduced.data[i];
			c2 = reduced.data[j];
			d = Math.sqrt((c1.lat-c2.lat)*(c1.lat-c2.lat)+(c1.lon-c2.lon)*(c1.lon-c2.lon));
			if (d < min_dist && d > 0) {
				min_dist = d;
				city1 = c1;
				city2 = c2;
			}
		}
	}

	return {"city1": city1.name, "city2": city2.name, "dist": min_dist};
}
 query : { "CountryID" : { "$ne" : 254 } }
 out : { inline : 1 }
 });


from:http://www.mongovue.com/2011/04/05/how-to-perform-mapreduce-operations-in-mongov