Example usage for com.mongodb.client.model Sorts ascending

List of usage examples for com.mongodb.client.model Sorts ascending

Introduction

In this page you can find the example usage for com.mongodb.client.model Sorts ascending.

Prototype

public static Bson ascending(final List<String> fieldNames) 

Source Link

Document

Create a sort specification for an ascending sort on the given fields.

Usage

From source file:com.egopulse.querydsl.mongodb.MongodbSerializer.java

License:Apache License

public Bson toSort(List<OrderSpecifier<?>> orderBys) {
    List<Bson> bsons = orderBys.stream().map(orderBy -> {
        Object key = orderBy.getTarget().accept(this, null);
        return orderBy.getOrder() == Order.ASC ? Sorts.ascending((String) key) : Sorts.descending((String) key);
    }).collect(Collectors.toList());
    return Sorts.orderBy(bsons);
}

From source file:com.github.cherimojava.data.mongo.query.QueryInvocationHandler.java

License:Apache License

private QuerySort addSortInformation(boolean asc) {
    curQueriedProperty.forEach(parameterProperty -> curSorts.add(parameterProperty.getMongoName()));
    if (asc) {//  www.jav a2  s . c  o m
        sorts.add(Sorts.ascending(curSorts));
    } else {
        sorts.add(Sorts.descending(curSorts));
    }
    curSorts.clear();
    curQueriedProperty.clear();
    return querySort.get();
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

private Bson orderBy(String s) {
    boolean descending = false;
    if (s.toUpperCase().endsWith(" ASC")) {
        s = s.substring(0, s.length() - " ASC".length()).trim();
        descending = false;//from w  ww. j a v  a2 s .  c o  m
    } else if (s.toUpperCase().endsWith(" DESC")) {
        s = s.substring(0, s.length() - " DESC".length()).trim();
        descending = true;
    } else
        s = s.trim();

    return descending ? Sorts.descending(s) : Sorts.ascending(s);
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.MongoDBSource.java

License:Apache License

private void prepareCursor(int maxBatchSize, String offsetField, String lastSourceOffset) {
    createMongoClient();//from  w w w.  j a v a  2 s.  c  o  m

    ObjectId offset;
    if (null == cursor) {
        if (null == lastSourceOffset || lastSourceOffset.isEmpty()) {
            offset = initialObjectId;
        } else {
            offset = new ObjectId(lastSourceOffset);
        }
        LOG.debug("Getting new cursor with params: {} {} {}", maxBatchSize, offsetField, lastSourceOffset);
        if (isCapped) {
            cursor = mongoCollection.find().filter(Filters.gt(offsetField, offset))
                    .cursorType(CursorType.TailableAwait).batchSize(maxBatchSize).iterator();
        } else {
            cursor = mongoCollection.find().filter(Filters.gt(offsetField, offset))
                    .sort(Sorts.ascending(offsetField)).cursorType(CursorType.NonTailable)
                    .batchSize(maxBatchSize).iterator();
        }
    }
}

From source file:io.lumeer.storage.mongodb.MongoDbStorageDialect.java

License:Open Source License

@Override
public DataSort documentFieldSort(final String fieldName, final int sortOrder) {
    if (sortOrder == 1) {
        return createSort(Sorts.ascending(fieldName));
    }//from  www . ja  v a  2 s.com

    if (sortOrder == -1) {
        return createSort(Sorts.descending(fieldName));
    }

    return null;
}

From source file:io.mandrel.metrics.impl.MongoMetricsRepository.java

License:Apache License

@Override
public Timeserie serie(String name) {
    Set<Data> results = StreamSupport.stream(timeseries.find(Filters.eq("type", name))
            .sort(Sorts.ascending("timestamp_hour")).limit(3).map(doc -> {
                LocalDateTime hour = LocalDateTime
                        .ofEpochSecond(((Date) doc.get("timestamp_hour")).getTime() / 1000, 0, ZoneOffset.UTC);
                Map<String, Long> values = (Map<String, Long>) doc.get("values");

                List<Data> mapped = values.entrySet().stream()
                        .map(elt -> Data.of(hour.plusMinutes(Long.valueOf(elt.getKey())), elt.getValue()))
                        .collect(Collectors.toList());
                return mapped;
            }).spliterator(), true).flatMap(elts -> elts.stream())
            .collect(TreeSet::new, Set::add, (left, right) -> {
                left.addAll(right);//from  ww w .  j av a 2 s  .  c om
            });

    Timeserie timeserie = new Timeserie();
    timeserie.addAll(results);
    return timeserie;
}

From source file:io.sip3.tapir.twig.mongo.query.SipSearchQuery.java

License:Apache License

@Override
public Bson sort() {
    if ((isBlank(caller) || isRegex(caller)) && (isBlank(callee) || isRegex(callee))) {
        return null;
    }/*  w  ww . j av  a  2s  . co m*/
    return Sorts.ascending("millis");
}

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   w w w  . jav a 2  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:mx.com.tecnomotum.testmongodb.Principal.java

public static void main(String args[]) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("test");
    MongoCollection<Document> coleccion = db.getCollection("restaurants");
    long totalElementos = coleccion.count();
    System.out.println("Total de elementos en la coleccin:" + totalElementos);

    // Obtener el primer elemento de la coleccin
    Document myDoc = coleccion.find().first();
    System.out.println("Primer object:" + myDoc.toJson());

    //Crear y aadir un nuevo documento a la coleccin
    Document nuevoDoc = new Document("name", "CARLITOS buf");
    nuevoDoc.append("borough", "Elvia");
    nuevoDoc.append("cuisine", "Gourmet");
    List<Document> puntuaciones = new ArrayList<>();
    Document punt = new Document();
    punt.append("grade", "A");
    punt.append("date", new Date());
    punt.append("score", 9);
    puntuaciones.add(punt);/*from w ww. ja v a  2 s  .c  om*/
    nuevoDoc.append("grades", puntuaciones);
    coleccion.insertOne(nuevoDoc);
    System.out.println("Total de elementos en la coleccin:" + coleccion.count());

    //OBtener un objeto de una coleccin
    Document objetoResp = coleccion.find(eq("name", "CARLITOS buf")).first();
    System.out.println("OBjeto encontrado:" + objetoResp.toJson());

    //OBtener la proyeccin del documento
    Document objetoResp2 = coleccion.find(eq("name", "CARLITOS buf"))
            .projection(fields(excludeId(), include("name"), include("grades.score"))).first();
    System.out.println("OBjeto encontrado:" + objetoResp2.toJson());

    //OBtener conjuntos de datos
    Block<Document> printBlock = new Block<Document>() {

        @Override
        public void apply(final Document doc) {
            System.out.println(doc.toJson());
        }
    };

    coleccion.find(eq("cuisine", "Hamburgers")).projection(fields(excludeId(), include("name")))
            .sort(Sorts.ascending("name")).forEach(printBlock);

}

From source file:org.eclipse.ditto.services.thingsearch.persistence.read.expression.visitors.GetSortBsonVisitor.java

License:Open Source License

/**
 * Builds singleton List (with always 1 entry) of a Bson document used for sorting based on the passed
 * {@code sortDirection} and {@code fieldName}.
 *
 * @param sortDirection the {@link SortDirection} to apply.
 * @param sortKey the sorting key.//from ww w .  j  av  a2  s  . com
 * @return the singleton List of a Bson sort document.
 */
private static List<Bson> getSortBson(final SortDirection sortDirection, final String sortKey) {
    requireNonNull(sortDirection);

    final Bson sort;
    switch (sortDirection) {
    case ASC:
        sort = Sorts.ascending(sortKey);
        break;
    case DESC:
        sort = Sorts.descending(sortKey);
        break;
    default:
        throw new IllegalStateException("Unknown SortDirection=" + sortDirection);
    }

    return Collections.singletonList(sort);
}