Kathandrax
Kathandrax

Reputation: 1054

Unexpected map reduce result with MongoDB 3.0

I am trying to implement a map reduce for my website (using MongoDB 3.0, Java 7).

To get me started, I just want to test the functionality but my collection is not affected by its output:

    String map = "function(){"
            + "emit(\"testValue\", [5, 5, 10]);"
        + "}" ;

    String reduce = "function(key, values){"
            + "return Array.sum(values);"
        + "}";

    // INPUT COLLECTION
    MongoCollection<Document> collection = 
    MongoDBManager.getMongoCollection("colTest");

    // OUTPUT COLLECTION
    MongoCollection<Document> index = 
    MongoDBManager.getMongoCollection("index");

    // MAP REDUCE
    collection.mapReduce(map, reduce)
        .action(MapReduceAction.REPLACE)
        .collectionName("index");


    // SEE CONTENT OF INDEX
    FindIterable<Document> result = index.find();

    MongoCursor<Document> cursor = result.iterator();

    while(cursor.hasNext()){
        Document current = cursor.next();
        System.out.println(current.toString());
    }
    cursor.close();

Here is the output of the println:

Document{{_id=58f4098537a734176b1c140f, testID=0}}

colTest is not empty. Here is a sample:

{"messages": [
    {
        "date": 1492308383230,
        "likesNumber": 1,
        "_id": {"$oid": "58f2d19f37a734176941a0ef"},
        "likers": ["allen"],
        "content": "a",
        "username": "paul"
    },
    {
        "date": 1492308345420,
        "likesNumber": 0,
        "_id": {"$oid": "58f2d17937a734172897ea8b"},
        "content": "ab",
        "username": "allen"
    },
    {
        "date": 1492308287884,
        "likesNumber": 0,
        "_id": {"$oid": "58f2d13f37a73416ef3d214e"},
        "content": "abc",
        "username": "john"
    }
]}

I would like the following output...

{"testValue" : 20}

... as many times as there are documents (3 in my sample) in colTest.

Why does my collection remain unchanged? Is there something wrong in the code or should I expect this result?

Upvotes: 0

Views: 563

Answers (1)

s7vr
s7vr

Reputation: 75914

You can try below MapReduce query.

String map = "function() {\n" +
            "                   var array = [5, 5, 10];\n" +
            "                   for (var idx = 0; idx < array.length; idx++) {\n" +
            "                       var key = 'testValue';\n" +
            "                       var value = array[idx];\n" +
            "                       emit(key, value);\n" +
            "                   }\n" +
            "             };";

String reduce = "function(key, values) {return Array.sum(values);};";

// MAP REDUCE
collection.mapReduce(map, reduce).action(MapReduceAction.REPLACE).collectionName("index").first();

The first signals the driver to run the query.

This will output something like

Document{{_id=testValue, value=20.0}}

Upvotes: 2

Related Questions