Example usage for com.mongodb DBCursor limit

List of usage examples for com.mongodb DBCursor limit

Introduction

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

Prototype

public DBCursor limit(final int limit) 

Source Link

Document

Limits the number of elements returned.

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);
    }/*  w ww.j  a  v  a 2 s .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 w w  w  . j  a  va  2  s .c o m
        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;//  w  w w .j  a  v a  2s  .co 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.stratio.connector.mongodb.core.engine.query.BasicLogicalWorkflowExecutor.java

License:Apache License

/**
 * Execute an usual query./*from www .  ja va  2 s .  c om*/
 *
 * @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:de.flapdoodle.mongoom.datastore.query.QueryResult.java

License:Apache License

@Override
public List<T> asList() {
    DBCursor find = getCursor();

    if (_limit > 0)
        find.limit(_limit);
    if (_skip > 0)
        find.skip(_skip);// w w  w  . ja v a  2s.c  o m

    return asList(find);
}

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

License:Apache License

@Override
public Iterator<T> iterator() {
    DBCursor find = getCursor();
    if (_limit > 0)
        find.limit(_limit);
    if (_skip > 0)
        find.skip(_skip);//  w ww  .  j a va2s. co  m
    return new TypedIterator<T>(this, _converter, find);
}

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  .  jav  a 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;
}

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  .com*/
        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

/**
 * /*from w  w w  . j  a  v  a 2  s  .c o  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:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSource.java

License:Open Source License

/**
 * Execute a query//  w  w  w.  ja  v a  2s . c om
 * 
 * @param request the mongoBD request model
 * @return DBCursor
 */
public DBCursor limitedQuery(MongoDBRequestModel request) {
    DBCursor cursor = null;
    try {
        DBObject dbObjectQuery = (DBObject) JSON.parse(request.getFilterString());
        DBObject dbObjectFields = (DBObject) JSON.parse(request.getKeysString());
        DBObject dbObjectSort = (DBObject) JSON.parse(request.getSortString());
        DB database = getDatabase();
        DBCollection collection = database.getCollection(request.getCollectionName());

        cursor = collection.find(dbObjectQuery, dbObjectFields).sort(dbObjectSort);
        cursor.skip(request.getStart());
        cursor.limit(request.getLimit());
        return cursor;
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        closeCursor(cursor);
    }
    return null;
}