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:net.kamradtfamily.mongorest.QueryServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doGet()");

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];/*from   w w w .ja v a  2s  .  com*/
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:NexT.db.mongo.DataModel.java

License:GNU General Public License

/**
 * Attempt to retrieve records from the specified collection using the
 * given query. If no records were found, null is returned instead.
 * @param collection The collection to query
 * @param query A DBObject representing the query parameters.
 * @param from From offset.//from   w ww. j a v a  2 s  . c  o m
 * @param limit Max. number of entries.
 * @return Null if no documents were found or an array of records.
 * @throws MongoException Thrown if the MongoWrapper has not been
 * initialized yet or if there was an error reading the objects from the db.
 */
public static DataModel[] getData(String collection, DBObject query, int from, int limit)
        throws MongoException {
    MongoWrapper wrapper = MongoWrapper.getInstance();
    if (wrapper == null)
        throw new MongoException("MongoWrapper has not been initiated.");
    DBCollection col = wrapper.getCollection(collection);
    DBCursor cursor = col.find(query).skip(from);
    if (limit != -1)
        cursor = cursor.limit(limit);
    List<DBObject> modelsList;
    DataModel[] models;
    try {
        modelsList = cursor.toArray();
        models = new DataModel[modelsList.size()];
        for (int i = 0; i < models.length; i++) {
            models[i] = new DataModel(col, modelsList.get(i));
        }
    } catch (Exception ex) {
        throw new MongoException("Error while retrieving Objects", ex);
    } finally {
        cursor.close();
    }
    if (models.length == 0)
        return null;
    else
        return models;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventRecord> getResults(String eventName, int skip, int limit) {
    DBObject queryObj = QueryBuilder.start().get();
    if (eventName != null) {
        queryObj.put(EventRecord.FIELD_EVENT_NAME, eventName);
    }//  www  .  java2 s . c  o  m
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventRecord> results = new ArrayList<EventRecord>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventRecord eventRecord = convertToEventRecord(obj);
            results.add(eventRecord);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "\n" + "Found results: \n" + "   Query:          " + queryObj + "\n" + "   Skip:           "
                        + skip + "\n" + "   Limit:          " + limit + "\n" + "   Results:        " + size);
    }
    return results;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventRecord> getResults(long startTime, long endTime, boolean chartOnly, int skip, int limit) {
    QueryBuilder queryBuilder = QueryBuilder.start().and(EventRecord.FIELD_START_TIME)
            .greaterThanEquals(new Date(startTime)).and(EventRecord.FIELD_START_TIME)
            .lessThan(new Date(endTime));
    if (chartOnly) {
        queryBuilder.and(EventRecord.FIELD_CHART).is(true);
    }//from  w  w  w  .java 2  s  .  co  m
    DBObject queryObj = queryBuilder.get();
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventRecord> results = new ArrayList<EventRecord>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventRecord eventRecord = convertToEventRecord(obj);
            results.add(eventRecord);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "\n" + "Found results: \n" + "   Query:          " + queryObj + "\n" + "   Skip:           "
                        + skip + "\n" + "   Limit:          " + limit + "\n" + "   Results:        " + size);
    }
    return results;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventDetails> getEventDetails(EventResultFilter filter, String filterEventName, int skip,
        int limit) {
    QueryBuilder queryBuilder = QueryBuilder.start();

    // apply filter
    switch (filter) {
    case Failed:/*from w  w w. j  ava 2  s.  c  o m*/
        queryBuilder.and(EventRecord.FIELD_SUCCESS).is(false);
        break;

    case Success:
        queryBuilder.and(EventRecord.FIELD_SUCCESS).is(true);
        break;
    default:
        break;
    }

    //apply event name filter
    if (null != filterEventName && !filterEventName.isEmpty()) {
        queryBuilder.and(EventRecord.FIELD_EVENT_NAME).is(filterEventName);
    }

    DBObject queryObj = queryBuilder.get();
    // sort descending to get the newest values first
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(-1))
            .get();
    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventDetails> results = new ArrayList<EventDetails>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventDetails eventDetails = convertToEventDetails(obj);
            results.add(eventDetails);
        }
    } finally {
        cursor.close();
    }

    return results;
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

protected void doFindAll(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in the collection
    DBObject query = null;/* w  w  w .j  a v a2 s.  co m*/
    // do not run around looking for a type converter unless there is a need for it
    if (exchange.getIn().getBody() != null) {
        query = exchange.getIn().getBody(DBObject.class);
    }
    DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class);

    // get the batch size and number to skip
    Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class);
    Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class);
    Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class);
    DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class);
    DBCursor ret = null;
    try {
        if (query == null && fieldFilter == null) {
            ret = dbCol.find(new BasicDBObject());
        } else if (fieldFilter == null) {
            ret = dbCol.find(query);
        } else {
            ret = dbCol.find(query, fieldFilter);
        }

        if (sortBy != null) {
            ret.sort(sortBy);
        }

        if (batchSize != null) {
            ret.batchSize(batchSize.intValue());
        }

        if (numToSkip != null) {
            ret.skip(numToSkip.intValue());
        }

        if (limit != null) {
            ret.limit(limit.intValue());
        }

        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll);
        resultMessage.setBody(ret.toArray());
        resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count());
        resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size());

    } catch (Exception e) {
        // rethrow the exception
        throw e;
    } finally {
        // make sure the cursor is closed
        if (ret != null) {
            ret.close();
        }
    }

}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Execute the query and return the result.
 *///ww  w.j  a  v  a 2 s  .  c o m
@Override
public Result<K, T> execute(final Query<K, T> query) {

    String[] fields = getFieldsToQuery(query.getFields());
    // Build the actual MongoDB query
    DBObject q = MongoDBQuery.toDBQuery(query);
    DBObject p = MongoDBQuery.toProjection(fields, mapping);

    if (query.getFilter() != null) {
        boolean succeeded = filterUtil.setFilter(q, query.getFilter(), this);
        if (succeeded) {
            // don't need local filter
            query.setLocalFilterEnabled(false);
        }
    }

    // Execute the query on the collection
    DBCursor cursor = mongoClientColl.find(q, p);
    if (query.getLimit() > 0)
        cursor = cursor.limit((int) query.getLimit());
    cursor.batchSize(100);
    cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);

    // Build the result
    MongoDBResult<K, T> mongoResult = new MongoDBResult<K, T>(this, query);
    mongoResult.setCursor(cursor);

    return mongoResult;
}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbDataContext.java

License:Apache License

private DBCursor getCursor(Table table, List<FilterItem> whereItems, int firstRow, int maxRows) {
    final DBCollection collection = _mongoDb.getCollection(table.getName());

    final DBObject query = createMongoDbQuery(table, whereItems);

    logger.info("Executing MongoDB 'find' query: {}", query);
    DBCursor cursor = collection.find(query);

    if (maxRows > 0) {
        cursor = cursor.limit(maxRows);
    }/*  w  ww .  j  a v  a 2  s.  co  m*/
    if (firstRow > 1) {
        final int skip = firstRow - 1;
        cursor = cursor.skip(skip);
    }
    return cursor;
}

From source file:org.apache.metamodel.mongodb.MongoDbDataContext.java

License:Apache License

private DataSet materializeMainSchemaTableInternal(Table table, Column[] columns, List<FilterItem> whereItems,
        int firstRow, int maxRows, boolean queryPostProcessed) {
    final DBCollection collection = _mongoDb.getCollection(table.getName());

    final DBObject query = createMongoDbQuery(table, whereItems);

    logger.info("Executing MongoDB 'find' query: {}", query);
    DBCursor cursor = collection.find(query);

    if (maxRows > 0) {
        cursor = cursor.limit(maxRows);
    }/*from  www .j  a v  a  2 s.co  m*/
    if (firstRow > 1) {
        final int skip = firstRow - 1;
        cursor = cursor.skip(skip);
    }

    return new MongoDbDataSet(cursor, columns, queryPostProcessed);
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.documentperevent.DocumentPerEventStorageStrategy.java

License:Apache License

@Override
protected DBCursor applyBatchSize(DBCursor cursor, int batchSize) {
    return cursor.limit(batchSize);
}