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:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/list", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataList(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "limit", required = false) Integer limit,
        @RequestParam(value = "sort", required = false) String sort,
        @RequestParam(value = "query", required = false) String query,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (!authRes.getBoolean(SUCCESS)) {
        return authRes.toString(4);
    }//from   w  ww  .j  a v a  2s.  co  m

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);
    DBCursor cursor;
    if (query != null && !query.isEmpty()) {
        Object queryObject = JSON.parse(query);
        cursor = dbCollection.find((BasicDBObject) queryObject);
    } else {
        cursor = dbCollection.find();
    }

    if (sort != null && !sort.isEmpty()) {
        Object sortObject = JSON.parse(sort);
        cursor.sort((BasicDBObject) sortObject);
    }

    if (limit != null && limit > 0) {
        if (page != null && page > 0) {
            cursor.skip((page - 1) * limit);
        }
        cursor.limit(limit);
    }
    List<DBObject> array = cursor.toArray();

    if (entityName.equals("User")) {
        for (DBObject dbObject : array) {
            dbObject.removeField(PASSWORD);
        }
    }

    for (DBObject dbObject : array) {
        dbRefToRelation(dbObject);
    }
    String json = JSON.serialize(array);

    // Indentation
    JSONArray jsonArr = new JSONArray(json);
    return jsonArr.toString(4);
}

From source file:com.restfiddle.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/list", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataList(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "limit", required = false) Integer limit,
        @RequestParam(value = "sort", required = false) String sort,
        @RequestParam(value = "query", required = false) String query) {
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);
    DBCursor cursor = null;
    if (query != null && !query.isEmpty()) {
        Object queryObject = JSON.parse(query);
        cursor = dbCollection.find((BasicDBObject) queryObject);
    } else {/*from ww  w. j ava  2  s. c  om*/
        cursor = dbCollection.find();
    }

    if (sort != null && !sort.isEmpty()) {
        Object sortObject = JSON.parse(sort);
        cursor.sort((BasicDBObject) sortObject);
    }

    if (limit != null && limit > 0) {
        if (page != null && page > 0) {
            cursor.skip((page - 1) * limit);
        }
        cursor.limit(limit);
    }
    List<DBObject> array = cursor.toArray();
    String json = JSON.serialize(array);

    // Indentation
    JSONArray jsonArr = new JSONArray(json);
    return jsonArr.toString(4);
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void doFind(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;//from  w  w  w  . j a  v  a  2 s .  c o m
    }
    Integer limit = (Integer) message.body().getNumber("limit");
    if (limit == null) {
        limit = -1;
    }
    Integer skip = (Integer) message.body().getNumber("skip");
    if (skip == null) {
        skip = -1;
    }
    Integer batchSize = (Integer) message.body().getNumber("batch_size");
    if (batchSize == null) {
        batchSize = 100;
    }
    Integer timeout = (Integer) message.body().getNumber("timeout");
    if (timeout == null || timeout < 0) {
        timeout = 10000; // 10 seconds
    }
    JsonObject matcher = message.body().getObject("matcher");
    JsonObject keys = message.body().getObject("keys");

    Object hint = message.body().getField("hint");
    Object sort = message.body().getField("sort");
    DBCollection coll = db.getCollection(collection);
    DBCursor cursor;
    if (matcher != null) {
        cursor = (keys == null) ? coll.find(jsonToDBObject(matcher))
                : coll.find(jsonToDBObject(matcher), jsonToDBObject(keys));
    } else {
        cursor = coll.find();
    }
    if (skip != -1) {
        cursor.skip(skip);
    }
    if (limit != -1) {
        cursor.limit(limit);
    }
    if (sort != null) {
        cursor.sort(sortObjectToDBObject(sort));
    }
    if (hint != null) {
        if (hint instanceof JsonObject) {
            cursor.hint(jsonToDBObject((JsonObject) hint));
        } else if (hint instanceof String) {
            cursor.hint((String) hint);
        } else {
            throw new IllegalArgumentException("Cannot handle type " + hint.getClass().getSimpleName());
        }
    }
    sendBatch(message, cursor, batchSize, timeout);
}

From source file:com.softlyinspired.jlw.reports.ReportReference.java

License:Open Source License

/**
 * Lists all the reports available/*w  w  w.  ja v a  2  s.c om*/
 * @return  Two dimensional array
 */
public String[][] listall() {
    String reportList[][] = new String[100][2];
    String tempId = new String();
    String tempTitle = new String();

    try {
        DBCollection coll = repoConnection.getReportsCollection();

        DBObject doc;
        BasicDBObject query = new BasicDBObject();
        BasicDBObject fields = new BasicDBObject();
        BasicDBObject sort = new BasicDBObject();

        fields.put("name", 1);
        fields.put("reportId", 1);
        fields.put("_id", 0);

        sort.put("reportId", 1);

        try {
            DBCursor allReports = coll.find(query, fields);
            allReports.sort(sort);
            reportCount = -1;
            while (allReports.hasNext()) {
                doc = allReports.next();
                reportCount = reportCount + 1;
                tempId = doc.get("reportId").toString();
                try {
                    tempTitle = doc.get("name").toString();
                } catch (Exception e) {
                    tempTitle = "";
                }

                reportList[reportCount][0] = tempId;
                reportList[reportCount][1] = tempTitle;
            }
        } catch (Exception e) {
            System.out.println("Report Missing");
        }
    } catch (Exception e) {
        JLWUtilities.scriptErrorMessage(e.toString());
    }
    return reportList;
}

From source file:com.softlyinspired.jlw.script.validationScript.java

License:Open Source License

/**
 * Lists all the scripts available//from w w  w  .  ja  va 2  s .com
 * @return  Two dimensional array
 */
public String[][] listall() {
    String scriptList[][] = new String[100][2];
    String tempId = new String();
    String tempTitle = new String();

    try {
        DBCollection coll = repoConnection.getScriptCollection();

        DBObject doc;
        BasicDBObject query = new BasicDBObject();
        BasicDBObject fields = new BasicDBObject();
        BasicDBObject sort = new BasicDBObject();

        fields.put("scriptText", 1);
        fields.put("scriptId", 1);
        fields.put("scriptTitle", 1);
        fields.put("_id", 0);

        sort.put("scriptId", 1);

        try {
            DBCursor allScripts = coll.find(query, fields); //.sort(sort);   
            allScripts.sort(sort);
            scriptCount = -1;
            while (allScripts.hasNext()) {
                doc = allScripts.next();
                scriptCount = scriptCount + 1;
                tempId = doc.get("scriptId").toString();
                doc.get("scriptText").toString();
                try {
                    tempTitle = doc.get("scriptTitle").toString();
                } catch (Exception e) {
                    tempTitle = "";
                }

                scriptList[scriptCount][0] = tempId;
                scriptList[scriptCount][1] = tempTitle;
            }

        } catch (Exception e) {
            System.out.println("Script Missing");
        }

    } catch (Exception e) {
        JLWUtilities.scriptErrorMessage(e.toString());

    }
    return scriptList;

}

From source file:com.stratio.connector.mongodb.core.engine.query.BasicLogicalWorkflowExecutor.java

License:Apache License

/**
 * Execute an usual query.//  w w  w .  jav a2s . c  o m
 *
 * @param mongoClient
 *            the MongoDB client.
 * @return the Crossdata ResultSet.
 * @throws MongoValidationException .
 * @throws ExecutionException
 *             if the execution fails or the query specified in the logical workflow is not supported.
 */
public ResultSet executeQuery(MongoClient mongoClient) throws ExecutionException {

    DB db = mongoClient.getDB(logicalWorkflowData.getProject().getCatalogName());
    DBCollection collection = db.getCollection(logicalWorkflowData.getProject().getTableName().getName());
    ResultSet resultSet = new ResultSet();
    resultSet.setColumnMetadata(
            MetaResultUtils.createMetadata(logicalWorkflowData.getProject(), logicalWorkflowData.getSelect()));

    if (logger.isDebugEnabled()) {
        logger.debug("Executing MongoQuery: " + query.get(0) + ", with fields: " + buildProject(false));
    }

    DBCursor cursor = collection.find(query.get(0), buildProject(false));

    if (logicalWorkflowData.getOrderBy() != null) {
        cursor = cursor.sort(buildOrderBy(false));
    }

    if (logicalWorkflowData.getLimit() != null) {
        cursor = cursor.limit(logicalWorkflowData.getLimit().getLimit());
    }

    DBObject rowDBObject;
    try {
        while (cursor.hasNext()) {
            rowDBObject = cursor.next();
            if (logger.isDebugEnabled()) {
                logger.debug("BResult: " + rowDBObject);
            }
            resultSet.add(MetaResultUtils.createRowWithAlias(rowDBObject, logicalWorkflowData.getSelect()));
        }
    } catch (MongoException e) {
        logger.error("Error executing a basic query :" + query.get(0) + ", with fields: " + buildProject(false)
                + "\n Error:" + e.getMessage());
        throw new MongoExecutionException(e.getMessage(), e);
    } finally {
        cursor.close();
    }

    return resultSet;
}

From source file:com.tomtom.speedtools.mongodb.MongoDBSorting.java

License:Apache License

/**
 * Method applies the sorting if any to given {@link DBCursor}.
 *
 * @param dbCursor {@link DBCursor} to apply sorting to.
 * @return {@link DBCursor} with sorting.
 *///ww w. j  a  va2 s. c  om
@Nonnull
public DBCursor apply(@Nonnull final DBCursor dbCursor) {
    assert dbCursor != null;

    // Check if sorting should be applied.
    if (!sortDBObject.isEmpty()) {
        return dbCursor.sort(sortDBObject);
    }
    return dbCursor;
}

From source file:de.flapdoodle.mongoom.datastore.query.QueryResult.java

License:Apache License

private DBCursor getCursor() {
    _logger.severe("Query: " + _query + ", View: " + _view);
    DBCursor ret = _view != null ? _dbCollection.find(_query, _view) : _dbCollection.find(_query);
    if (!_sort.isEmpty()) {
        DBObjectFactory sort = DBObjectFactory.start();
        for (String name : _sort.keySet()) {
            sort.set(name, _sort.get(name));
        }/*from   w w w.j a  va 2s  . co m*/
        DBObject sortBy = sort.get();
        _logger.severe("Sort: " + sortBy);
        ret.sort(sortBy);
    }
    return ret;
}

From source file:de.uni_koeln.spinfo.maalr.login.UserInfoDB.java

License:Apache License

List<MaalrUserInfo> getAllUsers(Role role, String text, String sortColumn, boolean sortAscending, int from,
        int length) {
    BasicDBObject query = new BasicDBObject();
    Pattern pattern = Pattern.compile(".*" + text + ".*", Pattern.CASE_INSENSITIVE);
    if (role != null) {
        query.put(Constants.Users.ROLE, role.toString());
    }/*w w  w  . ja  v a2s .c om*/
    if (text != null && text.trim().length() > 0) {
        BasicDBList attributes = new BasicDBList();
        DBObject firstName = new BasicDBObject();
        firstName.put(Constants.Users.FIRSTNAME, pattern);
        attributes.add(firstName);
        DBObject lastName = new BasicDBObject();
        lastName.put(Constants.Users.LASTNAME, pattern);
        attributes.add(lastName);
        DBObject login = new BasicDBObject();
        login.put(Constants.Users.LOGIN, pattern);
        attributes.add(login);
        query.append("$or", attributes);
    }
    DBCursor cursor = userCollection.find(query);
    if (sortColumn != null) {
        BasicDBObject sort = new BasicDBObject();
        sort.put(sortColumn, sortAscending ? 1 : -1);
        cursor.sort(sort);
    }
    cursor = cursor.skip(from).limit(length);
    List<MaalrUserInfo> all = new ArrayList<MaalrUserInfo>();
    while (cursor.hasNext()) {
        DBObject o = cursor.next();
        MaalrUserInfo user = new MaalrUserInfo(o);
        all.add(user);
    }
    cursor.close();
    return all;
}

From source file:de.uni_koeln.spinfo.maalr.mongo.core.Database.java

License:Apache License

private DBCursor query(String loginOrIP, Role role, Verification verification, String verifier, long startTime,
        long endTime, Status[] states, int limit, int offset, String orderField, boolean ascending) {
    // TODO: Add querying for 'current' state
    BasicDBObject query = new BasicDBObject();
    BasicDBObject attributes = new BasicDBObject();
    if (loginOrIP != null && loginOrIP.trim().length() > 0) {
        BasicDBList or = new BasicDBList();
        DBObject creator = new BasicDBObject();
        creator.put(QUERY_VERSION_CREATOR, loginOrIP);
        or.add(creator);//from  w w w  .  ja  va 2 s.com
        DBObject ip = new BasicDBObject();
        ip.put(QUERY_VERSION_IP, loginOrIP);
        or.add(ip);
        attributes.put("$or", or);
    }
    if (verifier != null && verifier.trim().length() > 0) {
        attributes.put(QUERY_VERSION_VERIFIER, verifier);
    }
    if (role != null) {
        attributes.put(QUERY_VERSION_ROLE, role.toString());
    }
    if (verification != null) {
        attributes.put(QUERY_VERSION_VERIFICATION, verification.toString());
    }
    if (states != null && states.length > 0) {
        BasicDBList or = new BasicDBList();
        for (Status s : states) {
            or.add(s.toString());
        }
        DBObject nestedOr = new BasicDBObject();
        nestedOr.put("$in", or);
        attributes.put(QUERY_VERSION_STATE, nestedOr);
    }
    if (startTime > 0) {
        attributes.put(QUERY_VERSION_TIMESTAMP, new BasicDBObject("$gt", startTime));
    }
    if (endTime > 0) {
        attributes.put(QUERY_VERSION_TIMESTAMP, new BasicDBObject("$lt", endTime));
    }
    if (startTime > 0 && endTime > 0) {
        DBObject obj = new BasicDBObject("$lt", endTime);
        obj.put("$gt", startTime);
        attributes.put(QUERY_VERSION_TIMESTAMP, obj);
    }
    DBCursor found;
    if (attributes.size() > 0) {
        BasicDBObject elemMatch = new BasicDBObject("$elemMatch", attributes);
        query.append(LexEntry.VERSIONS, elemMatch);
        // query.append("$and", attributes);
        // query.append("$elemMatch", attributes);
        found = entryCollection.find(query);
    } else {
        found = entryCollection.find();
    }
    if (orderField != null) {
        DBObject order = new BasicDBObject();
        order.put(LexEntry.VERSIONS + "." + orderField, ascending ? 1 : -1);
        found.sort(order);
    }
    // TODO: This is inefficient! However, it should be ok for
    // small queries, which is the expected usecase.
    if (offset > 0) {
        found = found.skip(offset);
    }
    if (limit > 0) {
        found = found.limit(limit);
    }
    return found;
}