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

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

Introduction

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

Prototype

public static Bson limit(final int limit) 

Source Link

Document

Creates a $limit 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.//from ww  w. j  a v  a  2  s .c  om
 *
 * @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.//www .  j  a  v a 2 s . c  om
 *
 * @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:org.eclipse.ditto.services.utils.persistence.mongo.streaming.MongoReadJournal.java

License:Open Source License

private Source<String, NotUsed> listJournalPidsAbove(final MongoCollection<Document> journal,
        final String start, final int batchSize, final Duration maxBackOff, final int maxRestarts) {

    final List<Bson> pipeline = new ArrayList<>(5);
    // optional match stage
    if (!start.isEmpty()) {
        pipeline.add(Aggregates.match(Filters.gt(PROCESSOR_ID, start)));
    }//  w  w  w. ja v a  2s  . c om

    // sort stage
    pipeline.add(Aggregates.sort(Sorts.ascending(PROCESSOR_ID)));

    // limit stage. It should come before group stage or MongoDB would scan the entire journal collection.
    pipeline.add(Aggregates.limit(batchSize));

    // group stage
    pipeline.add(Aggregates.group("$" + PROCESSOR_ID));

    // sort stage 2 -- order after group stage is not defined
    pipeline.add(Aggregates.sort(Sorts.ascending(ID)));

    final Duration minBackOff = Duration.ofSeconds(1L);
    final double randomFactor = 0.1;

    return RestartSource.onFailuresWithBackoff(minBackOff, maxBackOff, randomFactor, maxRestarts,
            () -> Source.fromPublisher(journal.aggregate(pipeline)).map(document -> document.getString(ID)));
}

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();
    }// w  w  w.  j  a v  a2  s .com

    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   w w  w. j  a 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.commons.datastore.mongodb.MongoDBQueryUtils.java

License:Apache License

public static Bson getLimit(QueryOptions options) {
    if (options.getInt(QueryOptions.LIMIT) > 0) {
        return Aggregates.limit(options.getInt(QueryOptions.LIMIT));
    }/*from   w  ww.  ja va2  s.co  m*/
    return null;
}

From source file:org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptor.java

License:Apache License

protected QueryResult rank(MongoDBCollection collection, Bson query, String groupByField, String idField,
        int numResults, boolean asc) {
    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }/*from  w w  w  .j  av  a  2  s  .  c  om*/

    if (groupByField.contains(",")) {
        // call to multiple rank if commas are present
        return rank(collection, query, Arrays.asList(groupByField.split(",")), idField, numResults, asc);
    } else {
        Bson match = Aggregates.match(query);
        Bson project = Aggregates.project(Projections.include(groupByField, idField));
        Bson group = Aggregates.group("$" + groupByField, Accumulators.sum("count", 1));
        Bson sort;
        if (asc) {
            sort = Aggregates.sort(Sorts.ascending("count"));
        } else {
            sort = Aggregates.sort(Sorts.descending("count"));
        }
        Bson limit = Aggregates.limit(numResults);

        return collection.aggregate(Arrays.asList(match, project, group, sort, limit), new QueryOptions());
    }
}

From source file:org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptor.java

License:Apache License

protected QueryResult rank(MongoDBCollection collection, Bson query, List<String> groupByField, String idField,
        int numResults, boolean asc) {

    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }//from ww  w  . j  av  a2 s.  com

    if (groupByField.size() == 1) {
        // if only one field then we call to simple rank
        return rank(collection, query, groupByField.get(0), idField, numResults, asc);
    } 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(idField);
        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 = Aggregates.group(id, Accumulators.sum("count", 1));
        Bson sort;
        if (asc) {
            sort = Aggregates.sort(Sorts.ascending("count"));
        } else {
            sort = Aggregates.sort(Sorts.descending("count"));
        }
        Bson limit = Aggregates.limit(numResults);

        return collection.aggregate(Arrays.asList(match, project, group, sort, limit), new QueryOptions());
    }
}