Example usage for com.mongodb.client.model Aggregates group

List of usage examples for com.mongodb.client.model Aggregates group

Introduction

In this page you can find the example usage for com.mongodb.client.model Aggregates group.

Prototype

public static <TExpression> Bson group(@Nullable final TExpression id,
        final List<BsonField> fieldAccumulators) 

Source Link

Document

Creates a $group pipeline stage for the specified filter

Usage

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

License:Open Source License

/**
 * The main method.//  www  .j  ava2 s.  c  o  m
 *
 * @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 ww  w .  j  a va 2 s  .  c o 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:module.script.epilung.SearchSamples.java

License:Open Source License

public SearchSamples() {

    // ===== Connection =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");
    MongoCollection<Document> collectionSamples = db.getCollection("samples");
    MongoCollection<Document> collectionPlatforms = db.getCollection("platforms");

    Bson filters = Filters.and(/*from   w ww. ja  v  a2 s  .  c o  m*/
            Filters.in("exp_group.id_platform", new String[] { "GPL13534", "GPL8490", "GPL21145" }),
            Filters.eq("exp_group.id_tissue_status", 1), Filters.ne("exp_group.id_topology", null));

    /*
    List<Document> list = collectionSamples
    .find(filters)
    .into(new ArrayList<Document>());
    */

    List<Document> list = collectionSamples.aggregate(Arrays.asList(Aggregates.match(filters),
            Aggregates.group("$exp_group.topology", Accumulators.sum("total", 1)),
            Aggregates.sort(Sorts.orderBy(Sorts.descending("total"))))).into(new ArrayList<Document>());

    for (int i = 0; i < list.size(); i++) {
        System.out.println((i + 1) + " " + list.get(i));
    }

    collectionPlatforms.find(Filters.regex("title", ".*ethyl.*")).forEach(printBlock);

    mongoClient.close();

}

From source file:module.test.SearchPlatforms.java

License:Open Source License

public SearchPlatforms() {

    // ===== Connection =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");
    MongoCollection<Document> collectionSamples = db.getCollection("sample");
    MongoCollection<Document> collectionPlatforms = db.getCollection("platform");

    List<Document> list = collectionSamples
            .aggregate(Arrays.asList(Aggregates.group("$exp_group.id_platform", Accumulators.sum("total", 1)),
                    Aggregates.sort(Sorts.orderBy(Sorts.descending("total")))))
            .into(new ArrayList<Document>());

    for (int i = 0; i < list.size(); i++) {
        System.out.println((i + 1) + " " + list.get(i));
    }/*from w w w. jav  a 2 s  .  c om*/

    // collectionPlatforms.find(Filters.regex("title", ".*ethyl.*")).forEach(printBlock);
    collectionPlatforms.find(Filters.eq("id_organism", "9606")).forEach(printBlock);

    mongoClient.close();

}

From source file:mongodb_teste.Jmongo.java

private void jBProfSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProfSearchActionPerformed
    // TODO add your handling code here:
    jshowProfSearch.setText("");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", jSearchName.getText()))),
                    Aggregates.unwind("$materias"),
                    Aggregates.group("$materias.nota", Accumulators.sum("total", 1)),
                    Aggregates.sort(new Document("total", -1))));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        jshowProfSearch.append(it.next().toString() + "\n");
    }//from  ww  w . java  2s . c om
    mongoClient.close();
}

From source file:mongodb_teste.MongoDB_teste.java

/**
 * @param args the command line arguments
 *//*  ww  w  . j  a v  a2 s .co m*/
public static void teste(String[] args) throws ParseException {
    // TODO code application logic here
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    /*db.getCollection("Professores").insertOne(
    new Document("nome", "Lana")
        .append("email", "123@ufu.com")
        .append("materias", asList(
                new Document()
                        .append("nome", "EDG")
                        .append("nota", "B"),
                new Document()
                        .append("nome", "BD")
                        .append("nota", "B")))
        .append("telefone", "435341543"));*/
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", "Miguel"))),
                    Aggregates.unwind("$materias"),
                    Aggregates.group("$materias.nota", Accumulators.sum("total", 1)),
                    Aggregates.sort(new Document("total", -1))));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        System.out.println(it.next().get("_id"));
    }
}

From source file:org.apache.rya.mongodb.aggregation.AggregationPipelineQueryNode.java

License:Apache License

/**
 * Add a $group step to filter out redundant solutions.
 * @return True if the distinct operation was successfully appended.
 *///from www .  ja  va 2  s .  co  m
public boolean distinct() {
    final List<String> key = new LinkedList<>();
    for (final String varName : bindingNames) {
        key.add(hashFieldExpr(varName));
    }
    final List<BsonField> reduceOps = new LinkedList<>();
    for (final String field : FIELDS) {
        reduceOps.add(new BsonField(field, new Document("$first", "$" + field)));
    }
    pipeline.add(Aggregates.group(new Document("$concat", key), reduceOps));
    return true;
}

From source file:org.opencb.cellbase.lib.impl.MongoDBAdaptor.java

License:Apache License

protected QueryResult groupBy(Bson query, String groupByField, String featureIdField, QueryOptions options) {
    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }/*from  w ww .  ja v  a  2  s.  c o  m*/

    if (groupByField.contains(",")) {
        // call to multiple groupBy if commas are present
        return groupBy(query, Arrays.asList(groupByField.split(",")), featureIdField, options);
    } else {
        Bson match = Aggregates.match(query);
        Bson project = Aggregates.project(Projections.include(groupByField, featureIdField));
        Bson group;
        if (options.getBoolean("count", false)) {
            group = Aggregates.group("$" + groupByField, Accumulators.sum("count", 1));
            return mongoDBCollection.aggregate(Arrays.asList(match, project, group), options);
        } else {
            // Limit the documents passed if count is false
            Bson limit = Aggregates.limit(options.getInt("limit", 10));
            group = Aggregates.group("$" + groupByField,
                    Accumulators.addToSet("features", "$" + featureIdField));
            // TODO change the default "_id" returned by mongodb to id
            return mongoDBCollection.aggregate(Arrays.asList(match, limit, project, group), options);
        }
    }
}

From source file:org.opencb.cellbase.lib.impl.MongoDBAdaptor.java

License:Apache License

protected QueryResult groupBy(Bson query, List<String> groupByField, String featureIdField,
        QueryOptions options) {//from   ww  w. ja  v a 2 s . c om
    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }

    if (groupByField.size() == 1) {
        // if only one field then we call to simple groupBy
        return groupBy(query, groupByField.get(0), featureIdField, options);
    } else {
        Bson match = Aggregates.match(query);
        // add all group-by fields to the projection together with the aggregation field name
        List<String> groupByFields = new ArrayList<>(groupByField);
        groupByFields.add(featureIdField);
        Bson project = Aggregates.project(Projections.include(groupByFields));
        // _id document creation to have the multiple id
        Document id = new Document();
        for (String s : groupByField) {
            id.append(s, "$" + s);
        }
        Bson group;
        if (options.getBoolean("count", false)) {
            group = Aggregates.group(id, Accumulators.sum("count", 1));
            return mongoDBCollection.aggregate(Arrays.asList(match, project, group), options);
        } else {
            // Limit the documents passed if count is false
            Bson limit = Aggregates.limit(options.getInt("limit", 10));
            group = Aggregates.group(id, Accumulators.addToSet("features", "$" + featureIdField));
            // TODO change the default "_id" returned by mongodb to id
            return mongoDBCollection.aggregate(Arrays.asList(match, limit, project, group), options);
        }
    }
}

From source file:org.opencb.cellbase.mongodb.impl.MongoDBAdaptor.java

License:Apache License

protected QueryResult groupBy(Bson query, String groupByField, String featureIdField, QueryOptions options) {
    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }//from   w  ww.j a va 2s  .c o  m

    if (groupByField.contains(",")) {
        // call to multiple groupBy if commas are present
        return groupBy(query, Arrays.asList(groupByField.split(",")), featureIdField, options);
    } else {
        Bson match = Aggregates.match(query);
        Bson project = Aggregates.project(Projections.include(groupByField, featureIdField));
        Bson group;
        if (options.getBoolean("count", false)) {
            group = Aggregates.group("$" + groupByField, Accumulators.sum("count", 1));
        } else {
            group = Aggregates.group("$" + groupByField,
                    Accumulators.addToSet("features", "$" + featureIdField));
        }
        return mongoDBCollection.aggregate(Arrays.asList(match, project, group), options);
    }
}