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

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

Introduction

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

Prototype

public static Bson sort(final Bson sort) 

Source Link

Document

Creates a $sort pipeline stage for the specified sort specification

Usage

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

License:Open Source License

/**
 * The main method./*  w  w w.ja  va2s.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 w w  w  .java 2s . 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:com.epam.dlab.backendapi.dao.azure.AzureBillingDAO.java

License:Apache License

private Bson sortCriteria() {
    return Aggregates.sort(Sorts.ascending(MongoKeyWords.prependId(MongoKeyWords.DLAB_USER),
            MongoKeyWords.prependId(MongoKeyWords.DLAB_ID),
            MongoKeyWords.prependId(MongoKeyWords.RESOURCE_TYPE),
            MongoKeyWords.prependId(MongoKeyWords.METER_CATEGORY)));
}

From source file:com.epam.dlab.billing.azure.AzureBillingDetailsService.java

License:Apache License

public void updateBillingDetails(String user) {
    log.debug("Updating billing details for user {}", user);

    try {//from   w w w  .  j a va  2 s.  c o m
        AggregateIterable<Document> aggregateIterable = mongoDbBillingClient.getDatabase()
                .getCollection(MongoKeyWords.BILLING_DETAILS)
                .aggregate(Lists.newArrayList(
                        Aggregates.match(Filters.and(Filters.eq(MongoKeyWords.DLAB_USER, user),
                                Filters.in(MongoKeyWords.RESOURCE_TYPE, DlabResourceType.EXPLORATORY.toString(),
                                        DlabResourceType.COMPUTATIONAL.toString(),
                                        DlabResourceType.VOLUME.toString()))),

                        Aggregates.group(
                                getGroupingFields(MongoKeyWords.DLAB_ID, MongoKeyWords.DLAB_USER,
                                        MongoKeyWords.EXPLORATORY_ID, MongoKeyWords.RESOURCE_TYPE,
                                        MongoKeyWords.RESOURCE_NAME, MongoKeyWords.COMPUTATIONAL_ID,
                                        MongoKeyWords.METER_CATEGORY),
                                Accumulators.sum(MongoKeyWords.COST,
                                        MongoKeyWords.prepend$(MongoKeyWords.COST)),
                                Accumulators.min(MongoKeyWords.USAGE_FROM,
                                        MongoKeyWords.prepend$(MongoKeyWords.USAGE_DAY)),
                                Accumulators.max(MongoKeyWords.USAGE_TO,
                                        MongoKeyWords.prepend$(MongoKeyWords.USAGE_DAY))),

                        Aggregates.sort(Sorts.ascending(MongoKeyWords.prependId(MongoKeyWords.RESOURCE_NAME),
                                MongoKeyWords.prependId(MongoKeyWords.METER_CATEGORY)))));

        updateBillingDetails(user, mapToDetails(aggregateIterable));
    } catch (RuntimeException e) {
        log.error("Updating billing details for user {} is failed", user, e);
    }
}

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(/*  w w w. j ava2s.  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.script.QueryAvailableData.java

License:Open Source License

public QueryAvailableData() {

    // ===== Service =====
    FormatService formatService = new FormatService();

    // ===== Session Mongo =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");

    MongoCollection<Document> collectionSeries = db.getCollection("series");
    MongoCollection<Document> collectionSamples = db.getCollection("samples");

    // ===== Print block =====
    Block<Document> printBlock = new Block<Document>() {
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }//from   ww  w  . jav a2  s  .c  om
    };

    // ===== Group by topology =====
    // db.getCollection('samples').aggregate({ $group: { "_id" : "$exp_group.topology", "total" : {$sum : 1} }}, {$sort : {total : -1}} )
    /*
    List<Document> listDocuments = collectionSamples.aggregate(
    Arrays.asList(
          Aggregates.group("$exp_group.topology", Accumulators.sum("total", 1)),
          Aggregates.sort(Sorts.orderBy(Sorts.descending("total")))
          ))
    .into(new ArrayList<Document>());
     */

    // ===== Group by sample =====
    /*
    List<Document> listSeries = collectionSeries
    .find()
    .projection(Projections.fields(Projections.include("title")))
    .sort(Sorts.ascending("_id"))
    .into(new ArrayList<Document>());
            
    for (Document doc : listSeries) {
            
       String idSeries = doc.getString("_id");
       Long nbSamples = collectionSamples.count((Filters.eq("series", idSeries)));
       doc.append("nbSamples", nbSamples);
    } 
    display(listSeries);
    */

    // === Export Geo for a list of idSeries ===

    // String[] listIdSeries = {"GSE11092","GSE13309", "GSE13159"};

    /*
    List<Document> docExpGroup = collectionSamples
    .find(Filters.in("series", listIdSeries))
    .projection(Projections.fields(Projections.include("exp_group"), Projections.excludeId()))
    .into(new ArrayList<Document>());
    // display(docExpGroup);
            
    List<String> header = formatService.extractHeader(docExpGroup, "exp_group");
    List<Object> data = formatService.extractData(docExpGroup, header, "exp_group");
    System.out.println(header);
    displayMatrix(data);
            
    */
    // List<Object> listObjects = formatService.convertHeterogeneousMongoDocuments(docExpGroup, "exp_group");
    // displayMatrix(listObjects);

    // List<Object> listObjects = formatService.convertHomogeneousMongoDocuments(listDocuments);

    // === Find series ===

    String[] listIdSamples = { "GSM80908", "GSM274639", "GSM274638", "GSM280213" };
    List<Document> listDocuments = collectionSamples
            .aggregate(Arrays.asList(Aggregates.match(Filters.in("_id", listIdSamples)),
                    Aggregates.group("$main_gse_number"),
                    Aggregates.sort(Sorts.orderBy(Sorts.ascending("main_gse_numbe")))))
            .into(new ArrayList<Document>());
    List<Object> listObjects = formatService.convertHomogeneousMongoDocuments(listDocuments);
    displayMatrix(listObjects);

    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));
    }//  ww w . j a  v  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.  j  a v a  2 s  .  c  o m
    mongoClient.close();
}

From source file:mongodb_teste.MongoDB_teste.java

/**
 * @param args the command line arguments
 *//*from   w w  w.  j a  v  a  2  s  .c o  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.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)));
    }//from  www.ja v  a2 s  .com

    // 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)));
}