Note that there are some explanatory texts on larger screens.

plurals
  1. POMongoDB's MapReduce function in Java returns null
    text
    copied!<p>I've some test data in my MongoDB:</p> <pre><code>&gt; db.test2.find() { "_id" : ObjectId("4e76ad8e9d7dc2438ab63dbb"), "name" : "John", "number" : 2 } { "_id" : ObjectId("4e76ad8e9d7dc2438ab63dbc"), "name" : "Jane", "number" : 1 } { "_id" : ObjectId("4e76ad8e9d7dc2438ab63dbd"), "name" : "John", "number" : 2 } { "_id" : ObjectId("4e76ad8e9d7dc2438ab63dbe"), "name" : "Jane", "number" : 1 } </code></pre> <p>And when I use following map/reduce function, MongoDB return the correct answer.</p> <pre><code>&gt; m = function() { emit(this.name, {count: 1, sum: this.number}); } &gt; r = function(key, values) { var n = { count: 0, sum: 0}; for (var i=0; i&lt;values.length; i++) { n.sum += values[i].sum; n.count += values[i].count; } return n; } &gt; db.test2.mapReduce(m, r, {out: 'test_col2'}) &gt; db.test_col2.find() { "_id" : "Jane", "value" : { "count" : 2, "sum" : 2 } } { "_id" : "John", "value" : { "count" : 2, "sum" : 4 } } </code></pre> <p>But If I test a following Java program, the result value is NULL.</p> <pre><code>public void run() throws Exception { m = new Mongo(HOST, PORT); db = m.getDB("test"); DBCollection col = db.getCollection("test2"); StringBuilder sbMap = new StringBuilder(); sbMap.append("function() {"); sbMap.append(" emit(this.name, {count:1, sum:this.number});"); sbMap.append("}"); StringBuilder sbReduce = new StringBuilder(); sbMap.append("function(key, values) {"); sbMap.append(" var n = { count: 0, sum: 0};"); sbMap.append(" for (var i=0; i&lt;values.length; i++) {"); sbMap.append(" n.count += values[i].count;"); sbMap.append(" n.sum += values[i].sum;"); sbMap.append(" }"); sbMap.append(" return n;"); sbMap.append("}"); MapReduceCommand cmd = new MapReduceCommand(col, sbMap.toString(), sbReduce.toString(), null, MapReduceCommand.OutputType.INLINE, null); MapReduceOutput out = col.mapReduce(cmd); for (DBObject o : out.results()) { System.out.println( o.toString() ); } } </code></pre> <p>Result:</p> <pre><code>{ "_id" : "Jane" , "value" : null } { "_id" : "John" , "value" : null } </code></pre> <p>What's the problem? I can't understand it. :(</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload