Example usage for com.mongodb.client MongoCollection aggregate

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

Introduction

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

Prototype

AggregateIterable<TDocument> aggregate(List<? extends Bson> pipeline);

Source Link

Document

Aggregates documents according to the specified aggregation pipeline.

Usage

From source file:analisissentimientos.SentimentAnnotated.java

public static void consultarDatasetsAnotados() {

    MongoDatabase mongoDB = new MongoClient(DB_SERVER, DB_PORT).getDatabase(DB_NAME);
    MongoCollection mongoCollection = mongoDB.getCollection(COLLECTION_NAME);

    AggregateIterable<Document> result = mongoCollection.aggregate(Arrays.asList(new Document("$group",
            new Document("_id", "$sentiment_score_annoted").append("count", new Document("$sum", 1)))));

    for (Document doc : result) {
        System.out.println(doc);/*from   w w  w .j  a va2s .  co  m*/
    }
}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java

License:Open Source License

/**
 * The main method.//from   w w  w. ja v a 2  s .  com
 *
 * @param args
 *            the arguments
 */
public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase numbersDB = client.getDatabase("students");
    MongoCollection<Document> grades = numbersDB.getCollection("grades");

    // Gets all the grades.
    MongoCursor<Document> cursor = grades.find(Filters.eq("type", "homework"))
            .sort(Sorts.ascending("student_id", "score")).iterator();

    Object previousStudentId = null;
    try {
        // Finds the lowest homework score.
        while (cursor.hasNext()) {
            Document entry = cursor.next();

            // If the student_id is different from the previous one, this 
            // means that this is the student's lowest graded homework 
            // (they are sorted by score for each student).
            if (!entry.get("student_id").equals(previousStudentId)) {
                Object id = entry.get("_id");
                grades.deleteOne(Filters.eq("_id", id));

            }

            // The current document ID becomes the new previous one.   
            previousStudentId = entry.get("student_id");
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = grades
                .aggregate(Arrays.asList(Aggregates.group("$student_id", Accumulators.avg("average", "$score")),
                        Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework31.MainClass.java

License:Open Source License

/**
 * The main method.//from   w  w w  .  j  a v a2  s. co m
 *
 * @param args
 *            the arguments
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("school");
    MongoCollection<Document> students = db.getCollection("students");

    // Gets all the students.
    MongoCursor<Document> cursor = students.find().iterator();

    try {
        while (cursor.hasNext()) {
            Document student = cursor.next();
            List<Document> scores = (List<Document>) student.get("scores");

            // Finds the lowest homework score.
            Document minScoreObj = null;
            double minScore = Double.MAX_VALUE;

            for (Document scoreDocument : scores) {
                double score = scoreDocument.getDouble("score");
                String type = scoreDocument.getString("type");

                // Swaps the scores.
                if (type.equals("homework") && score < minScore) {
                    minScore = score;
                    minScoreObj = scoreDocument;
                }
            }

            // Removes the lowest score.
            if (minScoreObj != null) {
                scores.remove(minScoreObj);
            }

            // Updates the record.
            students.updateOne(Filters.eq("_id", student.get("_id")),
                    new Document("$set", new Document("scores", scores)));
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = students.aggregate(Arrays.asList(Aggregates.unwind("$scores"),
                Aggregates.group("$_id", Accumulators.avg("average", "$scores.score")),
                Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:com.abhishek.mongodb.homework.week2.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/week2freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from  w  ww .  j  av a  2  s.  c o m*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.bluedragon.mongo.MongoCollectionAggregate.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData data = getNamedParam(argStruct, "pipeline", null);
    if (data == null)
        throwException(_session, "please specify a pipeline");

    List<Bson> pipelineList = new ArrayList<Bson>();

    if (data.getDataType() == cfData.CFARRAYDATA) {
        cfArrayData arrData = (cfArrayData) data;

        if (arrData.size() == 0)
            throwException(_session, "please specify at least one pipeline");

        for (int x = 0; x < arrData.size(); x++)
            pipelineList.add(getDocument(arrData.getData(x + 1)));

    } else {/*from w  w w. ja v  a 2  s . co m*/
        pipelineList.add(getDocument(data));
    }

    try {
        MongoCollection<Document> col = db.getCollection(collection);
        long start = System.currentTimeMillis();

        // Now we can run the query
        cfArrayData results = cfArrayData.createArray(1);

        col.aggregate(pipelineList).forEach(new Block<Document>() {

            @SuppressWarnings("rawtypes")
            @Override
            public void apply(Document doc) {
                try {
                    results.addElement(tagUtils.convertToCfData((Map) doc));
                } catch (cfmRunTimeException e) {
                }
            }

        });

        _session.getDebugRecorder().execMongo(col, "aggregate", null, System.currentTimeMillis() - start);

        return results;
    } catch (Exception e) {
        throwException(_session, e.getMessage());
        return null;
    }
}

From source file:com.demo.mongodb.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from  www .j  a v a2 s .c o m*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.enlightendev.mongodb.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from   ww w  . ja  v a  2 s.com*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereSimple() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(Document.parse("{$match: {\"prr\": 1}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();//from w  w  w.  j a v a2 s .c  o  m

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereManySimple() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(Document.parse("{$match: {\"prr\": 1, \"prg\": 89, \"csg\": 50}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();/*from  w w w.j  av a  2s.  c o  m*/

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object groupByWhereIn() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .aggregate(Arrays.asList(
                    Document.parse("{$match: {\"prr\": {$in: [" + DemoData.SCALAR_IN_2_AS_STRING + "]}}}"),
                    Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}")))
            .iterator();//  w  w w  .  j ava  2s  .co m

    Map<Integer, Map<Integer, Integer>> g = new HashMap<>();
    groupBy(g, cursor);
    cursor.close();
    return g;
}