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.groupon.jenkins.mongo.MongoRepository.java

License:Open Source License

protected <T> Iterable<T> find(DBObject query, DBObject fields, DBObject sort, Integer limit,
        Function<DBObject, T> transformer) {
    MongoClient client = getClient();//from www .j a v a  2s.co  m
    try {
        DBCursor cursor = fields == null ? getCollection(client).find(query)
                : getCollection(client).find(query, fields);
        if (sort != null) {
            cursor = cursor.sort(sort);
        }
        if (limit != null) {
            cursor = cursor.limit(limit);
        }
        List<T> result = new LinkedList<T>();

        try {
            while (cursor.hasNext()) {
                result.add(transformer.apply(cursor.next()));
            }
        } finally {
            cursor.close();
        }

        return result;
    } finally {
        client.close();
    }
}

From source file:com.heisenberg.mongo.MongoWorkflowStore.java

License:Apache License

@Override
public List<WorkflowImpl> loadWorkflows(WorkflowQueryImpl query) {
    BasicDBObject q = new BasicDBObject();
    if (query.id != null) {
        q.append(fields._id, new ObjectId(query.id));
    }/*from  w  w w  .  j a v  a  2 s  .com*/
    if (query.name != null) {
        q.append(fields.name, query.name);
    }
    List<WorkflowImpl> processes = new ArrayList<WorkflowImpl>();
    DBCursor cursor = find(q);
    if (query.limit != null) {
        cursor.limit(query.limit);
    }
    if (query.orderBy != null) {
        cursor.sort(writeOrderBy(query.orderBy));
    }
    while (cursor.hasNext()) {
        BasicDBObject dbProcess = (BasicDBObject) cursor.next();
        WorkflowImpl processDefinition = readProcessDefinition(dbProcess);
        processes.add(processDefinition);
    }
    return processes;
}

From source file:com.imaginea.mongodb.services.DocumentServiceImpl.java

License:Apache License

/**
 * Gets the list of documents inside a collection in a database in mongo to
 * which user is connected to./* w w  w.j  a  va 2  s.  c  o m*/
 * 
 * @param dbName
 *            Name of Database
 * @param collectionName
 *            Name of Collection from which to get all Documents
 * 
 * @param query
 *            query to be performed. In case of empty query {} return all
 *            docs.
 * 
 * @param keys
 *            Keys to be present in the resulted docs.
 * 
 * @param limit
 *            Number of docs to show.
 * 
 * @param skip
 *            Docs to skip from the front.
 * 
 * @return List of all documents.
 * @exception EmptyDatabaseNameException
 *                If database name is null
 * @exception EmptyCollectionNameException
 *                If Collection name is null
 * @exception UndefinedDatabaseException
 *                If database is not present
 * @exception UndefinedCollectionException
 *                If Collection is not present
 * @exception DatabaseException
 *                throw super type of UndefinedDatabaseException
 * @exception ValidationException
 *                throw super type of
 *                EmptyDatabaseNameException,EmptyCollectionNameException
 * @exception CollectionException
 *                throw super type of UndefinedCollectionException
 * @exception DocumentException
 *                exception while performing get doc list
 * 
 */

public ArrayList<DBObject> getQueriedDocsList(String dbName, String collectionName, DBObject query,
        DBObject keys, int limit, int skip)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {

    mongoInstance = mongoInstanceProvider.getMongoInstance();

    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database name is null");

    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }

    if (collectionName == null) {
        throw new EmptyCollectionNameException("Collection name is null");
    }
    if (collectionName.equals("")) {
        throw new EmptyCollectionNameException("Collection Name Empty");
    }

    ArrayList<DBObject> dataList = new ArrayList<DBObject>();
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB with name [" + dbName + "]DOES_NOT_EXIST");
        }

        if (!mongoInstance.getDB(dbName).getCollectionNames().contains(collectionName)) {
            throw new UndefinedCollectionException("Collection with name [" + collectionName
                    + "] DOES NOT EXIST in Database [" + dbName + "]");
        }
        if (keys.keySet().isEmpty()) {
            keys.put("_id", 1); // For empty keys return all _id of all docs
        }

        // Return Queried Documents
        DBCursor cursor = mongoInstance.getDB(dbName).getCollection(collectionName).find(query, keys);
        cursor.limit(limit);
        cursor.skip(skip);

        if (cursor.hasNext()) {
            while (cursor.hasNext()) {
                dataList.add(cursor.next());
            }
        }
    } catch (MongoException e) {
        throw new DocumentException(ErrorCodes.GET_DOCUMENT_LIST_EXCEPTION, "GET_DOCUMENT_LIST_EXCEPTION",
                e.getCause());
    }
    return dataList;

}

From source file:com.liferay.mongodb.hook.service.impl.MongoExpandoRowLocalServiceImpl.java

License:Open Source License

protected List<ExpandoRow> getRows(ExpandoTable expandoTable, int start, int end) {

    DBCollection dbCollection = MongoDBUtil.getCollection(expandoTable);

    DBCursor dbCursor = dbCollection.find(new BasicDBObject());

    if ((start != QueryUtil.ALL_POS) && (end != QueryUtil.ALL_POS)) {
        dbCursor.limit(start);
        dbCursor.limit(end - start);/*  w w  w .j a va  2  s  .  c om*/
    }

    List<ExpandoRow> expandoRows = new ArrayList<ExpandoRow>();

    for (DBObject expandoRowDBObject : dbCursor.toArray()) {
        ExpandoRow expandoRow = toExpandoRow(expandoRowDBObject, expandoTable);

        expandoRows.add(expandoRow);
    }

    return expandoRows;
}

From source file:com.linuxbox.enkive.message.search.mongodb.MongoMessageSearchService.java

License:Open Source License

public Set<String> searchImpl(Map<String, String> fields) throws MessageSearchException {
    Set<String> messageIds = new HashSet<String>();
    try {/*from w w  w  . j a  va 2  s . c  o  m*/
        DBObject query = buildQueryObject(fields);

        DBCursor results = messageColl.find(query, ID_ONLY_QUERY);
        String limitStr = fields.get(LIMIT_PARAMETER);
        if (limitStr != null) {
            limitStr = limitStr.trim();
            if (!limitStr.isEmpty()) {
                try {
                    int limit = Integer.parseInt(fields.get(LIMIT_PARAMETER));
                    results.limit(limit);
                } catch (NumberFormatException e) {
                    LOGGER.warn("Could not parse limit argument \"" + limitStr + "\" into integer.", e);
                }
            }
        }

        while (results.hasNext()) {
            DBObject message = results.next();
            messageIds.add((String) message.get("_id"));
        }
    } catch (EmptySearchResultsException e) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("A query that produced know results was executed.", e);
        }
    }

    return messageIds;
}

From source file:com.mysema.query.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, QueryModifiers modifiers,
        List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where));
    if (modifiers.getLimit() != null) {
        cursor.limit(modifiers.getLimit().intValue());
    }//from   w w w  . j  a va2s  . c  om
    if (modifiers.getOffset() != null) {
        cursor.skip(modifiers.getOffset().intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    return cursor;
}

From source file:com.querydsl.mongodb.AbstractMongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit);
    }/*from  w w  w  .jav a  2  s.  c om*/
    if (offset != null) {
        cursor.skip(offset);
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}

From source file:com.querydsl.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit.intValue());
    }/* w  ww  .j a  v  a  2  s .c  om*/
    if (offset != null) {
        cursor.skip(offset.intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}

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

License:Open Source License

@Override
public long find(CRUDOperationContext ctx, DBCollection coll, DBObject mongoQuery, DBObject mongoSort,
        Long from, Long to) {
    LOGGER.debug("Submitting query");
    DBCursor cursor = new FindCommand(null, coll, mongoQuery, null).execute();
    LOGGER.debug("Query evaluated");
    if (mongoSort != null) {
        cursor = cursor.sort(mongoSort);
        LOGGER.debug("Result set sorted");
    }// w  w w  . j av a  2  s.  c  om
    long ret = cursor.size();
    LOGGER.debug("Applying limits: {} - {}", from, to);
    if (from != null) {
        cursor.skip(from.intValue());
    }
    if (to != null) {
        cursor.limit(to.intValue() - (from == null ? 0 : from.intValue()) + 1);
    }
    LOGGER.debug("Retrieving results");
    List<DBObject> mongoResults = cursor.toArray();
    LOGGER.debug("Retrieved {} results", mongoResults.size());
    List<JsonDoc> jsonDocs = translator.toJson(mongoResults);
    ctx.addDocuments(jsonDocs);
    for (DocCtx doc : ctx.getDocuments()) {
        doc.setOperationPerformed(Operation.FIND);
    }
    LOGGER.debug("Translated DBObjects to json");
    return ret;
}

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 {/*from   ww  w  .j a v a 2  s  .c om*/
        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();
        }
    }
}