Example usage for com.mongodb DBCollection mapReduce

List of usage examples for com.mongodb DBCollection mapReduce

Introduction

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

Prototype

public MapReduceOutput mapReduce(final MapReduceCommand command) 

Source Link

Document

Allows you to run map-reduce aggregation operations over a collection.

Usage

From source file:com.Aleksandar.Zoric.MongoMain.java

public String mapReduceFunction() {
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    DB db = mongoClient.getDB("amarokforumdb");
    DBCollection collection = db.getCollection("comments");
    long count = db.getCollection("comments").count();

    System.out.println("Current amount of documents: " + count);

    String map = "function() { " + "var category; " + "var numOfDocuments = " + count + ";"
            + "for(i = 0; i < numOfDocuments; i++){ " + "if (numOfDocuments <= 100) {"
            + "category = 'New Comments'; }" + "else if(numOfDocuments > 100){"
            + "category = 'Old Comments'; }}" + "emit(category,1);};";

    String reduce = "function(key, values) { " + "var sum = 0; " + "values.forEach(function(doc) { "
            + "sum += 1; " + "}); " + "return {comments: sum};} ";

    MapReduceCommand cmd = new MapReduceCommand(collection, map, reduce, null,
            MapReduceCommand.OutputType.INLINE, null);

    MapReduceOutput out = collection.mapReduce(cmd);

    System.out.println("Mapreduce results");

    String result = null;/*w  w w  . j a  v  a2 s  . co  m*/

    for (DBObject o : out.results()) {
        result += o;

    }
    return result;
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private void createIterator() throws JRException {
    if (!queryObject.containsField(COLLECTION_NAME_KEY)) {
        throw new JRException("\"" + COLLECTION_NAME_KEY + "\" must be part of the query object");
    }//  ww w .j  a va2  s .  c  o  m
    DBObject findQueryObject = (DBObject) queryObject.get(FIND_QUERY_KEY);
    if (findQueryObject == null) {
        findQueryObject = new BasicDBObject();
    }
    if (queryObject.containsField(FIND_QUERY_REGEXP_KEY)) {
        DBObject regExpObject = (DBObject) queryObject.get(FIND_QUERY_REGEXP_KEY);
        String value, flags;
        int index;
        for (String key : regExpObject.keySet()) {
            value = (String) regExpObject.get(key);
            if (value.startsWith("/")) {
                value = value.substring(1, value.length());
            } else {
                throw new JRException("Regular expressions must start with: /");
            }
            if (!value.contains("/")) {
                throw new JRException("No ending symbol found: /");
            }
            index = value.lastIndexOf("/");
            flags = null;
            if (index == value.length() - 1) {
                value = value.substring(0, index);
            } else {
                flags = value.substring(index + 1, value.length());
                value = value.substring(0, index);
            }
            findQueryObject.put(key, Pattern.compile((flags != null ? "(?" + flags + ")" : "") + value));
        }
    }

    DBCollection collection = connection.getMongoDatabase()
            .getCollectionFromString((String) queryObject.removeField(COLLECTION_NAME_KEY));
    if (queryObject.containsField(MAP_REDUCE_KEY)) {
        Object value = queryObject.removeField(MAP_REDUCE_KEY);
        if (!(value instanceof DBObject)) {
            logger.error("MapReduce value must be a valid JSON object");
        } else {
            DBObject mapReduceObject = (DBObject) value;
            String map = validateProperty(mapReduceObject, MAP_KEY);
            String reduce = validateProperty(mapReduceObject, REDUCE_KEY);
            Object outObject = mapReduceObject.get(OUT_KEY);
            if (outObject == null) {
                throw new JRException("\"out\" cannot be null");
            }
            String collectionName = null;
            Object outDb = null;
            OutputType outputType = null;
            boolean hasOutputType = false;
            if (logger.isDebugEnabled()) {
                logger.debug("Out object: " + outObject + ". Type: " + outObject.getClass().getName());
            }
            if (outObject instanceof String) {
                collectionName = String.valueOf(outObject);
            } else if (outObject instanceof DBObject) {
                DBObject outDbObject = (DBObject) outObject;
                outDb = outDbObject.removeField(OUT_DB_KEY);
                Iterator<String> keysIterator = outDbObject.keySet().iterator();
                String type = null;
                if (keysIterator.hasNext()) {
                    type = keysIterator.next();
                    collectionName = String.valueOf(outDbObject.get(type));
                } else {
                    throw new JRException("\"out\" object cannot be empty");
                }
                type = type.toUpperCase();
                outputType = OutputType.valueOf(type);
                if (outputType == null) {
                    throw new JRException("Unknow output type: " + type);
                }
                hasOutputType = true;
                if (logger.isDebugEnabled()) {
                    logger.debug("outobject: " + outDbObject);
                    logger.debug("collectionName: " + collectionName);
                    logger.debug("outputType: " + outputType);
                }
            } else {
                throw new JRException("Unsupported type for \"out\": " + outObject.getClass().getName());
            }
            MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, collectionName,
                    hasOutputType ? outputType : OutputType.REPLACE, null);
            if (outDb != null) {
                mapReduceCommand.setOutputDB(String.valueOf(outDb));
            }
            Object finalizeObject = mapReduceObject.removeField(FINALIZE_KEY);
            if (finalizeObject != null) {
                mapReduceCommand.setFinalize(String.valueOf(finalizeObject));
            }
            MapReduceOutput mapReduceOutput = collection.mapReduce(mapReduceCommand);
            DBCollection mapReduceCollection = mapReduceOutput.getOutputCollection();
            if (mapReduceCollection != null) {
                collection = mapReduceCollection;
            }
        }
    }

    iterator = collection.find(findQueryObject, (DBObject) queryObject.get(FIND_FIELDS_KEY));
    if (queryObject.containsField(SORT_KEY)) {
        iterator = iterator.sort((DBObject) queryObject.get(SORT_KEY));
    }
    if (queryObject.containsField(LIMIT_KEY)) {
        Integer value = processInteger(queryObject.get(LIMIT_KEY));
        if (value != null) {
            iterator = iterator.limit(value.intValue());
        }
    }
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public List<BasicDBObject> mapReduceRaw(String map, String reduce, Filter filter) {
    long start = System.currentTimeMillis();
    DBObject query = this.getCachedFilter(filter);
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);

    MapReduceOutput output = elmnts.mapReduce(cmd);
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }/* www .  j  ava  2 s . co m*/
    //List<BasicDBObject> results = ArrayList<BasicDBObject> () ( output.results());getCommandResult().get( "results" );
    long end = System.currentTimeMillis();
    LOG.debug("The map-reduce job took {} seconds", (end - start) / 1000);
    return results;

}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public DBObject mapReduce(int key, String property, Filter filter, List<Integer> bins) {
    LOG.debug("Starting mapReduce for the following property: {}", property);
    long start = System.currentTimeMillis();
    Property prop = getCache().getProperty(property);
    String propType = prop.getType();
    String map = "";
    String map2 = "";
    String reduce = "";
    if (propType.equals(PropertyType.STRING.toString()) || propType.equals(PropertyType.BOOL.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property)\n" + "        {\n"
                + "            if (metadataRecord.status == 'CONFLICT'){\n" + "                emit({\n"
                + "                    property: property,\n" + "                    value: 'CONFLICT'\n"
                + "                }, 1);\n" + "            } else {\n" + "                emit({\n"
                + "                    property: property,\n"
                + "                    value: metadataRecord.sourcedValues[0].value\n"
                + "                }, 1);\n" + "\n" + "            }\n" + "            return;\n"
                + "        }\n" + "    }\n" + "    emit({\n" + "        property: property,\n"
                + "        value: 'Unknown'\n" + "        }, 1);\n" + "}";

        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    } else if (propType.equals(PropertyType.INTEGER.toString())
            || propType.equals(PropertyType.FLOAT.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    thresholds = "
                + getBinThresholds(bins) + ";\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property){\n"
                + "            if (metadataRecord.status == 'CONFLICT'){\n" + "                emit({\n"
                + "                    property: property,\n" + "                    value: 'CONFLICT'\n"
                + "                }, 1);\n" + "            } else {\n"
                + "                var val=metadataRecord.sourcedValues[0].value;\n"
                + "                var skipped=false;\n" + "                if (thresholds.length > 0)\n"
                + "                    for (t in thresholds){\n"
                + "                        threshold = thresholds[t];  \n"
                + "                        if (val>=threshold[0] && val<=threshold[1]){\n"
                + "                             emit({\n"
                + "                                property: property,\n"
                + "                                value: threshold[0]+'-'+threshold[1]\n"
                + "                            }, 1);\n" + "                             skipped=true;\n"
                + "                             break;\n" + "                         }\n"
                + "                    }\n" + "            }\n" + "            return;\n" + "        }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}";
        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    } else if (propType.equals(PropertyType.DATE.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property){\n"
                + "            if (metadataRecord.status == 'CONFLICT'){\n" + "                emit({\n"
                + "                    property: property,\n" + "                    value: 'CONFLICT'\n"
                + "                }, 1);\n" + "            } else {\n"
                + "                var date = new Date(metadataRecord.sourcedValues[0].value);\n"
                + "                var val=date.getFullYear();\n" + "                emit({\n"
                + "                    property: property,\n" + "                    value: val\n"
                + "                }, 1);\n" + "            }\n" + "            return;\n" + "        }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}";

        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    }/* w w  w .  j  av a 2  s  .  com*/
    DBObject query = this.getCachedFilter(filter);
    LOG.debug("Filter query is:\n{}", query);
    String queryString = query.toString();
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);
    MapReduceOutput output = elmnts.mapReduce(cmd);
    // List<BasicDBObject> results = (List<BasicDBObject>) output.getCommandResult().get( "results" );
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }

    LOG.debug("MapReduce produced {} results", results.size());
    DBCollection histCollection = this.db.getCollection(TBL_HISTOGRAMS);
    BasicDBObject old = new BasicDBObject("_id", key);
    BasicDBObject res = new BasicDBObject(old.toMap());
    res.put("results", results);
    histCollection.update(old, res, true, false);

    DBCursor cursor = histCollection.find(new BasicDBObject("_id", key));

    if (cursor.count() == 0) {
        return null;
    }
    long end = System.currentTimeMillis();
    LOG.debug("MapReduce took {} seconds", (end - start) / 1000);
    return (DBObject) cursor.next().get("results");
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public DBObject mapReduceAllValues(int key, String property, Filter filter, List<Integer> bins) {
    LOG.debug("Starting mapReduce for the following property: {}", property);
    long start = System.currentTimeMillis();
    Property prop = getCache().getProperty(property);
    String propType = prop.getType();
    String map = "";
    String map2 = "";
    String reduce = "";
    if (propType.equals(PropertyType.STRING.toString()) || propType.equals(PropertyType.BOOL.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property)\n" + "        {\n"
                + "            for (i in metadataRecord.sourcedValues)\n" + "            {\n"
                + "                sv=metadataRecord.sourcedValues[i];\n" + "                emit({\n"
                + "                    property: property,\n" + "                    value: sv.value\n"
                + "                }, 1);\n" + "\n" + "            }\n" + "            return;\n"
                + "        }\n" + "    }\n" + "    emit({\n" + "        property: property,\n"
                + "        value: 'Unknown'\n" + "        }, 1);\n" + "}";

        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    } else if (propType.equals(PropertyType.INTEGER.toString())
            || propType.equals(PropertyType.FLOAT.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    thresholds = "
                + getBinThresholds(bins) + ";\n" + "    for (mr in this.metadata)" + "    {\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property)" + "        {\n"
                + "           for (i in metadataRecord.sourcedValues)" + "           {\n"
                + "                sv=metadataRecord.sourcedValues[i];\n"
                + "                var val=sv.value;\n" + "                if (thresholds.length > 0)\n"
                + "                    for (t in thresholds){\n"
                + "                        threshold = thresholds[t];  \n"
                + "                        if (val>=threshold[0] && val<=threshold[1]){\n"
                + "                             emit({\n"
                + "                                property: property,\n"
                + "                                value: threshold[0]+'-'+threshold[1]\n"
                + "                            }, 1);\n" + "                         }\n"
                + "                    }\n" + "            }\n" + "            return;\n" + "         }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}";
        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    } else if (propType.equals(PropertyType.DATE.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property){\n"
                + "           for (i in metadataRecord.sourcedValues){\n"
                + "               sv=metadataRecord.sourcedValues[i];\n"
                + "               var date = new Date(sv.value);\n"
                + "               var val=date.getFullYear();\n" + "               emit({\n"
                + "                    property: property,\n" + "                    value: val\n"
                + "               }, 1);\n" + "            }\n" + "            return;\n" + "        }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}";

        reduce = "function reduce(key, values) {\n" + "    var res = 0;\n"
                + "    values.forEach(function(v) {\n" + "        res += v;\n" + "    });\n"
                + "    return res;\n" + "}";

    }//from  w  ww .ja  va  2 s  . com
    DBObject query = this.getCachedFilter(filter);
    LOG.debug("Filter query is:\n{}", query);
    String queryString = query.toString();
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);
    MapReduceOutput output = elmnts.mapReduce(cmd);
    // List<BasicDBObject> results = (List<BasicDBObject>) output.getCommandResult().get( "results" );
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }

    LOG.debug("MapReduce produced {} results", results.size());
    DBCollection histCollection = this.db.getCollection(TBL_HISTOGRAMS);
    BasicDBObject old = new BasicDBObject("_id", key);
    BasicDBObject res = new BasicDBObject(old.toMap());
    res.put("results", results);
    histCollection.update(old, res, true, false);

    DBCursor cursor = histCollection.find(new BasicDBObject("_id", key));

    if (cursor.count() == 0) {
        return null;
    }
    long end = System.currentTimeMillis();
    LOG.debug("MapReduce took {} seconds", (end - start) / 1000);
    return (DBObject) cursor.next().get("results");
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public DBObject mapReduceStats(int key, String property, Filter filter) {
    LOG.debug("Starting mapReduceStats for the following property: {}", property);
    long start = System.currentTimeMillis();
    Property prop = getCache().getProperty(property);
    String propType = prop.getType();
    String map = "";
    String reduce = "";
    String finalize = "";
    if (propType.equals(PropertyType.INTEGER.toString()) || propType.equals(PropertyType.FLOAT.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property){\n" + "            {\n"
                + "                emit({\n" + "                    property: property,\n"
                + "                    value: property\n" + "                }, \n" + "                {\n"
                + "                    sum: metadataRecord.sourcedValues[0].value,\n"
                + "                    min: metadataRecord.sourcedValues[0].value,\n"
                + "                    max: metadataRecord.sourcedValues[0].value,\n"
                + "                    count: 1,\n" + "                    diff: 0\n" + "                }\n"
                + "                )\n" + "            }\n" + "            return;\n" + "        }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}\n";
        reduce = "function reduce(key, values) {\n" + "var a = values[0];\n"
                + "        for (var i = 1; i < values.length; i++) {\n" + "            var b = values[i];\n"
                + "            var delta = a.sum / a.count - b.sum / b.count;\n"
                + "            var weight = (a.count * b.count) / (a.count + b.count);\n"
                + "            a.diff += b.diff + delta * delta * weight;\n"
                + "            a.sum = b.sum*1+ a.sum*1;\n" + "            a.count += b.count;\n"
                + "            a.min = Math.min(a.min, b.min);\n"
                + "            a.max = Math.max(a.max, b.max);\n" + "        }\n" + "return a;" + "}"

        ;//from ww w . j  av  a  2s  .  c o  m
        finalize = "function finalize(key, value) {\n" + "    value.avg = value.sum / value.count;\n"
                + "    value.variance = value.diff / value.count;\n"
                + "    value.stddev = Math.sqrt(value.variance);\n" + "    return value;\n" + "}";

    }
    DBObject query = this.getCachedFilter(filter);
    LOG.debug("filter query is:\n{}", query);
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);
    cmd.setFinalize(finalize);
    MapReduceOutput output = elmnts.mapReduce(cmd);

    //List<BasicDBObject> results = (List<BasicDBObject>) output.getCommandResult().get( "results" );
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }

    LOG.debug("MapReduce produced {} results", results.size());
    DBCollection histCollection = this.db.getCollection(TBL_HISTOGRAMS);
    BasicDBObject old = new BasicDBObject("_id", key);
    BasicDBObject res = new BasicDBObject(old.toMap());
    res.put("results", results);
    histCollection.update(old, res, true, false);

    DBCursor cursor = histCollection.find(new BasicDBObject("_id", key));

    if (cursor.count() == 0) {
        return null;
    }
    long end = System.currentTimeMillis();
    LOG.debug("The map-reduce job took {} seconds", (end - start) / 1000);
    return (DBObject) cursor.next().get("results");
}

From source file:edu.wayne.cs.fms.controller.CRUD.java

public static ArrayList MapReduce(String colName, String map, String reduce, String finalize,
        MongoClient mongoClient) {//from   ww  w  .ja v a  2 s . com
    //MongoClient mongoClient = Connector.connect("localhost", 27017);
    DB db = mongoClient.getDB("project");
    DBCollection temp = db.getCollection(colName);

    ArrayList result = new ArrayList();
    MapReduceCommand cmd = new MapReduceCommand(temp, map, reduce, null, MapReduceCommand.OutputType.INLINE,
            null);

    if (finalize != null) {
        cmd.setFinalize(finalize);
    }

    MapReduceOutput out = temp.mapReduce(cmd);

    for (DBObject o : out.results()) {
        result.add(o.toString());
    }
    System.out.println("Done");
    //mongoClient.close();
    return result;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Runs a map-reduce aggregation over a collection and saves the result to a temporary collection, which is deleted at the end
 * of the execution. The results of the operation are returned to the caller in a list of {@code BasicDBObject}.
 * @param collection - collection whose objects are searched
 * @param mapFn - map function/* www  .j av  a2s .  co m*/
 * @param reduceFn - reduce function
 * @param query - (optional) specifies the selection criteria using query operators for determining the documents input to the 
 *        map function. Set this parameter to {@code null} to use all documents in the collection
 * @return a list of {@code BasicDBObject} which contains the results of this map reduce operation.
 * @see <a href="http://cookbook.mongodb.org/patterns/pivot/">The MongoDB Cookbook - Pivot Data with Map reduce</a>
 */
public List<BasicDBObject> mapReduce(final String collection, final String mapFn, final String reduceFn,
        final @Nullable DBObject query) {
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    checkArgument(isNotBlank(mapFn), "Uninitialized or map function");
    checkArgument(isNotBlank(reduceFn), "Uninitialized or reduce function");
    final List<BasicDBObject> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    final DBCollection tmpCol = tmpCollection();
    try {
        final MapReduceCommand command = new MapReduceCommand(dbcol, mapFn, reduceFn, tmpCol.getName(), REDUCE,
                query);
        final MapReduceOutput output = dbcol.mapReduce(command);
        final Iterable<DBObject> results = output.results();
        for (final DBObject result : results) {
            list.add((BasicDBObject) result);
        }
    } catch (Exception e) {
        throw new IllegalStateException("Failed to execute map-reduce operation", e);
    } finally {
        try {
            tmpCol.drop();
        } catch (Exception mdbe) {
            LOGGER.warn("Failed to drop temporary collection", mdbe);
        }
    }
    return list;
}

From source file:govt_import_export.Order.java

private void sort_cars() {
    MongoClient mongo = null;/*w  w  w  . j a  va2  s  . co  m*/
    try {
        mongo = new MongoClient("localhost", 27017);
        //get database
    } catch (UnknownHostException | MongoException e) {
    }
    String[] st = new String[10];
    st[0] = "HYUNDAI";
    st[1] = "MARUTISUZUKI";
    st[2] = "NISSAN";
    st[3] = "BAJAJ";
    st[4] = "KTM";
    st[5] = "VOLKSVAGEN";
    DB db = mongo.getDB("AUTOMOBILEXPO");
    DBCollection table;

    ArrayList<Order> arr = new ArrayList<Order>();
    for (int j = 0; j < 6; j++) {
        table = db.getCollection(st[j]);

        if (table.findOne() != null) {
            String map = "function () {" + "emit(this.model,this.Units);" + "}";
            String reduce;
            reduce = "function (key,value) { " + "return Array.sum(value)}";

            MapReduceCommand cmd = new MapReduceCommand(table, map, reduce, null,
                    MapReduceCommand.OutputType.INLINE, null);

            MapReduceOutput out = table.mapReduce(cmd);
            String str;
            for (DBObject o : out.results()) {
                str = o.get("value").toString().trim();
                System.out.println(str);
                int i = 0;
                // var i=(int)(Convert.ToDouble("1.2"));
                //int a = int.Parse("1.2".Split('.')[0]);
                if (!str.equals(null)) {
                    Float f = Float.parseFloat(str);
                    i = (int) Math.ceil(f);
                    arr.add(new Order(o.get("_id").toString(), i) {

                        @Override
                        public int compare(Order o1, Order o2) {
                            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                        }

                        @Override
                        public int compareTo(Order o) {
                            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                        }
                    });
                }
            }
        }

    }
    Collections.sort(arr, new Order() {
    });
    for (Order a : arr)
        System.out.println(" " + a.getid() + " " + a.getval());
    this.dispose();
    Sorted s = new Sorted(arr);
    s.setVisible(true);

}

From source file:govt_import_export.export.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    JLabel p = new JLabel();
    MongoClient mongo = null;/*from  ww  w  . j ava  2s. c  om*/
    try {
        mongo = new MongoClient("localhost", 27017);
        //get database
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    catch (MongoException e) {
        e.printStackTrace();
    }
    DB db = mongo.getDB("AUTOMOBILEXPO");
    DBCollection table = db.getCollection(manufac);
    String map = "function () {" + "emit(this.model,this.Units);" + "}";
    String reduce = "function (key, values) { " + "return Array.sum(values)}";

    MapReduceCommand cmd = new MapReduceCommand(table, map, reduce, null, MapReduceCommand.OutputType.INLINE,
            null);

    MapReduceOutput out = table.mapReduce(cmd);

    for (DBObject o : out.results()) {
        System.out.println(o.toString());
    }

}