Example usage for com.mongodb DBCursor skip

List of usage examples for com.mongodb DBCursor skip

Introduction

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

Prototype

public DBCursor skip(final int numberOfElements) 

Source Link

Document

Discards a given number of elements at the beginning of the cursor.

Usage

From source file:com.redhat.lightblue.mongo.crud.BasicDocFinder.java

License:Open Source License

@Override
public long find(CRUDOperationContext ctx, DBCollection coll, DBObject mongoQuery, DBObject mongoProjection,
        DBObject mongoSort, Long from, Long to) {
    LOGGER.debug("Submitting query {}", mongoQuery);

    long executionTime = System.currentTimeMillis();
    DBCursor cursor = null;
    boolean cursorInUse = false;
    try {/* www .  j av  a  2  s  . c  o  m*/
        cursor = coll.find(mongoQuery, mongoProjection);
        if (readPreference != null) {
            cursor.setReadPreference(readPreference);
        }

        if (ctx.isLimitQueryTime() && maxQueryTimeMS > 0) {
            cursor.maxTime(maxQueryTimeMS, TimeUnit.MILLISECONDS);
        }

        executionTime = System.currentTimeMillis() - executionTime;

        LOGGER.debug("Query evaluated");
        if (mongoSort != null) {
            cursor = cursor.sort(mongoSort);
            LOGGER.debug("Result set sorted");
        }

        LOGGER.debug("Applying limits: {} - {}", from, to);
        boolean retrieve = true;
        int nRetrieve = 0;
        int numMatched = 0;
        // f and t are from and to indexes, both inclusive
        int f = from == null ? 0 : from.intValue();
        if (f < 0) {
            f = 0;
        }
        cursor.skip(f);
        if (ctx.isComputeCounts()) {
            numMatched = cursor.count();
        }
        int t;
        if (to != null) {
            t = to.intValue();
            if (t < f) {
                retrieve = false;
            } else {
                cursor.limit(nRetrieve = t - f + 1);
            }
        } else {
            if (ctx.isComputeCounts()) {
                t = numMatched - 1;
                nRetrieve = numMatched - f;
            } else {
                t = Integer.MAX_VALUE;
            }
        }
        if (retrieve) {
            LOGGER.debug("Retrieving results");
            CursorStream stream = new CursorStream(cursor, translator, mongoQuery, executionTime, f, t);
            ctx.setDocumentStream(stream);
            cursorInUse = true;
        } else {
            ctx.setDocumentStream(new ListDocumentStream<DocCtx>(new ArrayList<>()));
        }
        if (RESULTSET_LOGGER.isDebugEnabled() && (executionTime > 100)) {
            RESULTSET_LOGGER.debug("execution_time={}, query={}, from={}, to={}", executionTime, mongoQuery, f,
                    t);
        }
        return numMatched;
    } finally {
        if (cursor != null && !cursorInUse) {
            cursor.close();
        }
    }
}

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  . ja  v  a2  s  . c  o  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  av a2  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 2s. com
    }
    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.tomtom.speedtools.mongodb.MongoDBPaging.java

License:Apache License

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

    // Check if paging should be applied.
    if ((offset != DEFAULT_OFFSET) || (count != DEFAULT_COUNT)) {
        return dbCursor.skip(offset).limit(count);
    }
    return dbCursor;
}

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);//  www. j a v  a 2s .  c  om
    if (_skip > 0)
        find.skip(_skip);

    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);/*ww w  . ja v  a 2s .  co  m*/
    if (_skip > 0)
        find.skip(_skip);
    return new TypedIterator<T>(this, _converter, find);
}

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());
    }// ww w.  j a  va 2  s. 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);/* ww w.  j a  va 2s .c  om*/
        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:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * // ww  w.j a v a2  s .com
 * @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);
    }
}