Example usage for com.mongodb.client MongoCollection mapReduce

List of usage examples for com.mongodb.client MongoCollection mapReduce

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection mapReduce.

Prototype

MapReduceIterable<TDocument> mapReduce(String mapFunction, String reduceFunction);

Source Link

Document

Aggregates documents according to the specified map-reduce function.

Usage

From source file:Example4.java

License:Open Source License

public static void main(String args[])
        throws IOException, ParseException, DScabiClientException, DScabiException, java.text.ParseException {
    System.out.println("Example4");

    DMeta meta = new DMeta("localhost", "5000");
    Dao dao = new Dao(meta);

    // The below examples demonstrate accessing MongoCollection and doing
    // Map/Reduce on the MongoCollection

    // Create Table
    try {/*  ww w  .ja  va2 s.co  m*/
        if (false == dao.tableExists("scabi:MyOrg.MyTables:Table1")) {
            System.out.println("Create Table");
            DTable t = dao.createTable("scabi:MyOrg.MyTables:Table1");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Get existing Table
    DTable table = dao.getTable("scabi:MyOrg.MyTables:Table1");

    // Insert data
    if (0 == table.count()) {
        try {
            System.out.println("Insert data");
            DDocument d = new DDocument();
            d.append("EmployeeName", "Karthik").append("EmployeeNumber", "3000").append("Age", 40);
            table.insert(d);

            d.clear();
            d.append("EmployeeName", "Jayaprakash").append("EmployeeNumber", "3001").append("Age", 35);
            table.insert(d);

            d.clear();
            d.append("EmployeeName", "Arun").append("EmployeeNumber", "3002").append("Age", 30);
            table.insert(d);

            d.clear();
            d.append("EmployeeName", "Balaji").append("EmployeeNumber", "3003").append("Age", 35);
            table.insert(d);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Access underlying MongoCollection
    MongoCollection<Document> c = table.getCollection();

    // Example to directly do Map/Reduce on the MongoCollection
    String map = "function() { for (var key in this) { emit(key, null); } }";
    String reduce = "function(key, s) { if (\"Age\" == key) return true; else return false; }";

    MapReduceIterable<Document> out = c.mapReduce(map, reduce);
    for (Document o : out) {
        System.out.println("Key name is : " + o.get("_id").toString());
        System.out.println(o.toString());
    }

    dao.close();
    meta.close();

}