-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongodbMapReduceWithNodeJSExample.js
120 lines (96 loc) · 3.08 KB
/
mongodbMapReduceWithNodeJSExample.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// node mongodbMapReduceWithNodeJSExample.js
var mongodb_db = require('mongodb').Db;
var mongodb_connection = require('mongodb').Connection;
var mongodb_server = require('mongodb').Server;
var host = 'localhost';
var port = mongodb_connection.DEFAULT_PORT;
var db = new mongodb_db('sampleDB', new mongodb_server(host, port, {}), {
native_parser : false
});
// --------------
function init(callback) {
db.open(function() {
db.dropCollection('sample', function(err, result) {
seedData(callback);
});
});
}
function seedData(callback) {
db.collection('sample', function(err, collection) {
if(err)
throw err;
var count = 4;
var clbk = function() {
if(--count === 0) {
collection.find({}, function(err, cursor) {
cursor.toArray(function(err, items) {
console.log("\n\nSample values:")
console.log(JSON.stringify(items) + '\n\n');
callback();
});
});
}
};
collection.save({
name : "Rouben Meschian",
age : 32,
gender : "male",
nationality : "Armenian"
}, clbk);
collection.save({
name : "Michael Jackson",
age : 42,
gender : "male",
nationality : "American"
}, clbk);
collection.save({
name : "Armina Meschian",
age : 2,
gender : "female",
nationality : "Armenian"
}, clbk);
collection.save({
name : "Brendan Eich",
age : 32,
gender : "male",
nationality : "American"
}, clbk);
});
}
init(function() {
// compute avg age of each nationality
// db.close();
// process.exit(0);
var map = function() {
emit(this.nationality, this.age);
};
var reduce = function(key, values) {
var sum = 0, count = values.length;
values.forEach(function(val) {
sum += val;
});
return {
nationality : key,
avg_age : sum / count
};
};
var MR = {
mapreduce : "sample",
out : "mapReduceResultCollection",
map : map.toString(),
reduce : reduce.toString()
};
console.log("\nexecuting mapreduce");
db.executeDbCommand(MR, function(err, dbres) {
db.collection('mapReduceResultCollection', function(err, collection) {
collection.find({}, function(err, cursor) {
cursor.toArray(function(err, items) {
console.log("\n\nresults of mapreduce:")
console.log(JSON.stringify(items));
db.close();
process.exit(0);
});
});
});
});
});