Example usage for com.mongodb DBCursor sort

List of usage examples for com.mongodb DBCursor sort

Introduction

In this page you can find the example usage for com.mongodb DBCursor sort.

Prototype

public DBCursor sort(final DBObject orderBy) 

Source Link

Document

Sorts this cursor's elements.

Usage

From source file:es.bsc.amon.DBManager.java

License:Open Source License

public BasicDBList find(String collectionName, DBObject query, DBObject orderby, Integer limit) {
    BasicDBList result = new BasicDBList();

    DBCursor c = null;
    if (query == null) {
        c = database.getCollection(collectionName).find();
    } else {/*from   www .jav a  2 s  .c  o m*/
        c = database.getCollection(collectionName).find(query);
    }

    if (orderby == null) {
        c.sort(orderby);
    }

    if (limit != null && limit > 0) {
        c = c.limit(limit);
    }

    while (c.hasNext()) {
        result.add(c.next());
    }
    c.close();
    return result;
}

From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * //  w  ww .ja v a  2s.  co m
 * @param httpHeaders
 * @param collection
 * @param dbObj1
 * @param dbObj2
 * @param successMsg
 * @param sort
 * @param limit
 * @param skip
 * @param count
 * @return
 */
public DBObject executeFindQuery(HttpHeaders httpHeaders, String dbName, String collection, DBObject dbObj1,
        DBObject dbObj2, String successMsg, String sort, int limit, int skip, boolean count) {
    try {
        if (dbName == null)
            dbName = getDbNameFromHTTPHeader(httpHeaders);
        DBCursor cursorDoc = null;
        if (count) {
            BasicDBObject dbObject = new BasicDBObject();
            dbObject.put("count", DBConn.getConn(dbName).getCollection(collection).find(dbObj1).count());
            return jSON2Rrn.createJSON(dbObject, successMsg);
        } else {
            if (dbObj2 == null) {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1);
            } else {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1, dbObj2);
            }
        }
        if (sort != null) {
            try {
                DBObject sortObj = (DBObject) JSON.parse(sort);
                cursorDoc = cursorDoc.sort(sortObj);
            } catch (Exception e) {
                return jSON2Rrn.createJSONError("Error in filtering JSON sorting object: " + sort, e);
            }
        }
        if (skip != 0)
            cursorDoc = cursorDoc.skip(skip);
        if (limit != 0)
            cursorDoc = cursorDoc.limit(limit);

        Vector<DBObject> recordsVec = new Vector<DBObject>();
        while (cursorDoc.hasNext()) {
            DBObject obj = cursorDoc.next();

            if (collection.equalsIgnoreCase(MongoDistributions.COL_DISTRIBUTIONS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoDistributions.COL_DISTRIBUTIONS);
            } else if (collection.equalsIgnoreCase(MongoConsumptionModels.COL_CONSMODELS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoConsumptionModels.COL_CONSMODELS);
            } else if (collection.equalsIgnoreCase(MongoPricingPolicy.COL_PRICING)) {
                PricingPolicy pp = new PricingPolicy(obj);
                double oneKw24Cost = pp.calcOneKw24();
                obj.put("onekw24", oneKw24Cost);
            }

            if (obj.containsField("_id"))
                obj = addChildrenCounts(httpHeaders, collection, obj);
            recordsVec.add(obj);
        }
        cursorDoc.close();
        return jSON2Rrn.createJSON(recordsVec, successMsg);
    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError("MongoQueryError: Cannot execute find query for collection: "
                + collection + " with qKey=" + dbObj1 + " and qValue=" + dbObj2, e);
    }
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Returns a view of the objects in the collection that contains the specified range. The objects are sorted by the key in ascending order. 
 * Optionally, the number of objects found in the collection is returned to the caller. Also, the returned fields can be filtered.
 * @param sortCriteria - objects in the collection are sorted with this criteria
 * @param collection - collection where the objects are searched
 * @param start - starting index//ww  w.j av a 2 s.c  om
 * @param size - maximum number of objects returned
 * @param query - the expression to be used to query the collection
 * @param projection - (optional) Specifies the fields to return using projection operators. To return all fields in the matching document, 
 *                     omit this parameter
 * @param count - (optional) is updated with the number of objects in the database
 * @return a view of the objects in the collection that contains the specified range
 */
public List<BasicDBObject> list(final DBObject sortCriteria, final String collection, final int start,
        final int size, final @Nullable DBObject query, final @Nullable DBObject projection,
        final @Nullable MutableLong count) {
    checkArgument(sortCriteria != null, "Uninitialized sort criteria");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final List<BasicDBObject> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    final DBCursor cursor = dbcol.find(query != null ? query : new BasicDBObject(),
            projection != null ? projection : new BasicDBObject());
    cursor.sort(sortCriteria);
    cursor.skip(start).limit(size);
    try {
        while (cursor.hasNext()) {
            list.add((BasicDBObject) cursor.next());
        }
    } finally {
        cursor.close();
    }
    if (count != null) {
        count.setValue(cursor.count());
    }
    return list;
}

From source file:eu.itesla_project.histodb.server.ITeslaDatasource.java

License:Mozilla Public License

@Override
protected DBCursor getDataCursor(Map<String, ?> ranges, int start, int count,
        ColumnDescriptor[] columnDescriptors, Map<String, INDEXTYPE> indexTypes) {
    DBCursor cursor = super.getDataCursor(ranges, start, count, columnDescriptors, indexTypes);

    //TODO use indexes on filters ; check http://emptysqua.re/blog/optimizing-mongodb-compound-indexes/
    // example : {horizon:1,datetime:1,CHOO17GROUP_1_NGU_SM_P:1}

    return cursor.sort(new BasicDBObject("datetime", 1));
}

From source file:eu.itesla_project.histodb.server.ITeslaRulesDatasource.java

License:Mozilla Public License

@Override
protected DBCursor getDataCursor(Map<String, ?> ranges, int start, int count,
        ColumnDescriptor[] columnDescriptors, Map<String, INDEXTYPE> indexTypes) {
    DBCursor cursor = super.getDataCursor(ranges, start, count, columnDescriptors, indexTypes);

    return cursor.sort(new BasicDBObject("datetime", 1));
}

From source file:fr.cirad.web.controller.gigwa.base.AbstractVariantController.java

License:Open Source License

/**
 * Builds the variant rows./* www.j  a va2  s. co m*/
 *
 * @param mongoTemplate the mongo template
 * @param variantsToBuildRowsFor the variants to build rows for
 * @param sortBy the sort by
 * @param sortDir the sort dir
 * @param page the page
 * @param size the size
 * @param variantFieldMap the variant field map
 * @param runDataFieldMap the run data field map
 * @return the array list
 */
private ArrayList<Object[]> buildVariantRows(MongoTemplate mongoTemplate, DBCursor variantsToBuildRowsFor,
        String sortBy, String sortDir, int page, int size, HashMap<Integer, String> variantFieldMap,
        Map<Integer, String> runDataFieldMap) {
    if (sortBy != null && sortBy.length() > 0) {
        String cleanSortField = sortBy.replaceFirst("%23", "");
        variantsToBuildRowsFor.sort(
                new BasicDBObject(cleanSortField, Integer.valueOf("DESC".equalsIgnoreCase(sortDir) ? -1 : 1)));
    }
    variantsToBuildRowsFor.skip(page * size).limit(size);

    ArrayList<Object[]> variantRows = new ArrayList<Object[]>();
    HashMap<Comparable, Object[]> variantIdToRowMap = new HashMap<Comparable, Object[]>();

    Collection<Comparable> currentVariants = new ArrayList<Comparable>();
    while (variantsToBuildRowsFor.hasNext()) {
        DBObject record = variantsToBuildRowsFor.next();
        Object[] aRow = new Object[variantFieldMap.size() + runDataFieldMap.size()];
        for (int i : variantFieldMap.keySet())
            aRow[i] = Helper.readPossiblyNestedField(record, variantFieldMap.get(i));
        variantRows.add(aRow);
        variantIdToRowMap.put((Comparable) aRow[0], aRow);
        currentVariants.add((Comparable) aRow[0]);
    }

    if (!runDataFieldMap.isEmpty()) { // Query on VariantRunData so we can fill run-related fields
        ArrayList<DBObject> genotypingDataAggregationParams2 = new ArrayList<DBObject>();
        genotypingDataAggregationParams2.add(new BasicDBObject("$match", new BasicDBObject(
                "_id." + VariantRunDataId.FIELDNAME_VARIANT_ID, new BasicDBObject("$in", currentVariants))));
        DBObject project = new BasicDBObject();
        for (String sField : runDataFieldMap.values())
            project.put(sField.replaceAll("\\.", ""), "$" + sField);
        genotypingDataAggregationParams2.add(new BasicDBObject("$project", project));

        //         long beforeQuery = System.currentTimeMillis();
        Cursor genotypingDataCursor = mongoTemplate
                .getCollection(MongoTemplateManager.getMongoCollectionName(VariantRunData.class))
                .aggregate(genotypingDataAggregationParams2,
                        AggregationOptions.builder().allowDiskUse(true).build());
        while (genotypingDataCursor.hasNext()) {
            DBObject record = genotypingDataCursor.next();
            Object[] aRow = variantIdToRowMap.get(
                    Helper.readPossiblyNestedField(record, "_id." + VariantRunDataId.FIELDNAME_VARIANT_ID));
            for (int fieldIndex : runDataFieldMap.keySet())
                aRow[fieldIndex] = record.get(runDataFieldMap.get(fieldIndex).replaceAll("\\.", ""));
        }
        //         LOG.debug("Genotyping data main query treated in " + (System.currentTimeMillis() - beforeQuery) + "ms");
    }
    return variantRows;
}

From source file:fr.gouv.vitam.cases.DbRequest.java

License:Open Source License

/**
 * In MongoDB : <br/> //from  ww w .  ja  v a2  s. c om
 * find(Query, Projection).sort(SortFilter).skip(SkipFilter).limit(LimitFilter);<br/>
 * In addition, one shall limit the scan by: <br/>
 * find(Query, Projection)._addSpecial( "$maxscan", highlimit)
 *   .sort(SortFilter).skip(SkipFilter).limit(LimitFilter);
 * 
 * @param query
 * @param result to be filtered using query
 * @return the new result or null if the same
 */
private ResultInterface lastFilter(final AbstractQueryParser query, final ResultInterface result) {
    if (simulate) {
        return null;
    }
    boolean filter = (query.getLimit() > 0 || query.getOffset() > 0);
    if (!filter) {
        return null;
    }
    ObjectNode orderBy = query.getOrderBy();
    if (GlobalDatas.PRINT_REQUEST) {
        LOGGER.warn("Req1LevelMD Filter on: Limit {} Offset {} OrderBy {}", query.getLimit(), query.getOffset(),
                orderBy);
    }
    final ResultInterface subresult = CassandraAccess.createOneResult();
    BasicDBObject inClause = getInClauseForField(DAip.ID, result.getCurrentDaip());
    final DBCursor cursor = mdAccess.daips.collection.find(inClause, ID_NBCHILD);
    if (query.getLimit() > 0) {
        cursor.limit(query.getLimit());
    }
    if (query.getOffset() > 0) {
        cursor.skip(query.getOffset());
    }
    if (orderBy != null) {
        // orderBy is used only if limit and/or offset is set
        cursor.sort((DBObject) orderBy);
    }
    long tempCount = 0;
    while (cursor.hasNext()) {
        final DAip maip = (DAip) cursor.next();
        final String mid = maip.getId();
        subresult.getCurrentDaip().add(mid);
        tempCount += maip.getLong(DAip.NBCHILD);
    }
    cursor.close();
    if (subresult.getCurrentDaip().containsAll(result.getCurrentDaip())) {
        // same so don't change it
        return null;
    }
    subresult.setNbSubNodes(tempCount);
    // Not updateMinMax since result is not "valid" path but node UUID and not needed
    subresult.setMinLevel(result.getMinLevel());
    subresult.setMaxLevel(result.getMaxLevel());
    subresult.setLoaded(true);
    if (GlobalDatas.PRINT_REQUEST) {
        subresult.putBeforeSave();
        LOGGER.warn("Filtered: {}", subresult);
    }
    return subresult;
}

From source file:fr.gouv.vitam.mdbes.DbRequest.java

License:Open Source License

/**
 * In MongoDB : <br/> //from   w w w  . j  a v a 2 s . c om
 * find(Query, Projection).sort(SortFilter).skip(SkipFilter).limit(LimitFilter);<br/>
 * In addition, one shall limit the scan by: <br/>
 * find(Query, Projection)._addSpecial( "$maxscan", highlimit)
 *   .sort(SortFilter).skip(SkipFilter).limit(LimitFilter);
 * 
 * @param query
 * @param result to be filtered using query
 * @return the new result or null if the same
 */
private ResultInterface lastFilter(final AbstractQueryParser query, final ResultInterface result) {
    if (simulate) {
        return null;
    }
    boolean filter = (query.getLimit() > 0 || query.getOffset() > 0);
    if (!filter) {
        return null;
    }
    ObjectNode orderBy = query.getOrderBy();
    if (GlobalDatas.PRINT_REQUEST) {
        LOGGER.warn("Req1LevelMD Filter on: Limit {} Offset {} OrderBy {}", query.getLimit(), query.getOffset(),
                orderBy);
    }
    final ResultInterface subresult = MongoDbAccess.createOneResult();
    BasicDBObject inClause = getInClauseForField(DAip.ID, result.getCurrentDaip());
    final DBCursor cursor = mdAccess.daips.collection.find(inClause, ID_NBCHILD);
    if (query.getLimit() > 0) {
        cursor.limit(query.getLimit());
    }
    if (query.getOffset() > 0) {
        cursor.skip(query.getOffset());
    }
    if (orderBy != null) {
        // orderBy is used only if limit and/or offset is set
        cursor.sort((DBObject) orderBy);
    }
    long tempCount = 0;
    while (cursor.hasNext()) {
        final DAip maip = (DAip) cursor.next();
        final String mid = maip.getId();
        subresult.getCurrentDaip().add(mid);
        tempCount += maip.getLong(DAip.NBCHILD);
    }
    cursor.close();
    if (subresult.getCurrentDaip().containsAll(result.getCurrentDaip())) {
        // same so don't change it
        return null;
    }
    subresult.setNbSubNodes(tempCount);
    // Not updateMinMax since result is not "valid" path but node UUID and not needed
    subresult.setMinLevel(result.getMinLevel());
    subresult.setMaxLevel(result.getMaxLevel());
    subresult.setLoaded(true);
    if (GlobalDatas.PRINT_REQUEST) {
        subresult.putBeforeSave();
        LOGGER.warn("Filtered: {}", subresult);
    }
    return subresult;
}

From source file:in.mtap.iincube.mongoapi.MongoReader.java

License:Apache License

private DBCursor getCursor() {
    DBCollection collection = collectionFactory.get();
    assertNotNull(queryObject, "findQuery == null");
    DBCursor cursor;
    if (fields != null) {
        BasicDBObject selectFields = new BasicDBObject();
        for (String field : fields) {
            selectFields.append(field, 1);
        }//  w  ww  .j av a  2 s .  c o m
        cursor = collection.find(queryObject, selectFields);
    } else {
        cursor = collection.find(queryObject);
    }
    if (skip > 0)
        cursor.skip(skip);
    if (limit > 0)
        cursor.limit(limit);
    if (sortObject != null)
        cursor.sort(sortObject);
    return cursor;
}

From source file:io.liveoak.mongo.MongoCollectionResource.java

License:Open Source License

@Override
public Collection<Resource> members(RequestContext ctx) throws Exception {

    LinkedList<Resource> members = new LinkedList<>();

    DBObject returnFields = new BasicDBObject();
    if (ctx.returnFields() != null && !ctx.returnFields().child(LiveOak.MEMBERS).isEmpty()) {
        ReturnFields membersReturnFields = ctx.returnFields().child(LiveOak.MEMBERS);
        if (!membersReturnFields.isAll()) {
            membersReturnFields.forEach((fieldName) -> {
                returnFields.put(fieldName, true);
            });//from  w  ww .java 2s. c om
        }
    }

    DBCursor dbCursor = dbCollection.find(queryObject, returnFields);

    ResourceParams resourceParams = ctx.resourceParams();
    if (resourceParams != null && resourceParams.contains("hint")) {
        String hint = resourceParams.value("hint");
        if (hint.startsWith("{")) {
            try {
                DBObject hintObject = (DBObject) JSON.parse(hint);
                dbCursor.hint(hintObject);
            } catch (Exception e) {
                throw new NotAcceptableException(uri().toString(),
                        "Invalid JSON format for the 'hint' parameter", e);
            }
        } else {
            dbCursor.hint(hint);
        }
    }

    if (explainQuery) {
        members.add(new MongoEmbeddedObjectResource(this, dbCursor.explain()));
    } else {
        Sorting sorting = ctx.sorting();
        if (sorting != null) {
            BasicDBObject sortingObject = new BasicDBObject();
            for (Sorting.Spec spec : sorting) {
                sortingObject.append(spec.name(), spec.ascending() ? 1 : -1);
            }
            dbCursor = dbCursor.sort(sortingObject);
        }

        Pagination pagination = ctx.pagination();
        if (pagination != null) {
            dbCursor.limit(pagination.limit());
            dbCursor.skip(pagination.offset());
        }

        try {
            dbCursor.hasNext();
        } catch (Exception e) {
            throw new ResourceProcessingException(
                    "Exception encountered trying to fetch data from the Mongo Database", e);
        }

        dbCursor.forEach((dbObject) -> {
            members.add(new MongoBaseObjectResource(this, dbObject));
        });
    }

    return members;
}