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:org.mongolink.domain.query.CursorParameter.java

License:Open Source License

DBCursor apply(DBCursor cursor) {
    cursor = cursor.limit(limit).skip(skip).sort(orderBy);
    return cursor;
}

From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java

License:Open Source License

@Override
public List<StatAction> getActions(Query query) throws StatsEngineException {
    List<StatAction> actions = new ArrayList<StatAction>();
    try {//from  w  w w.  jav  a2s .  c  om
        DBCollection targetActions = getTargetActionsCollection();
        DBObject queryDoc = EMPTY_DOC;
        QueryFilter filter = query.getFilter(QueryField.CLIENT_ID);
        if (filter != null && !filter.isEmpty()) {
            queryDoc = MongoUtil.createDoc(EVENT_CLIENT_ID, filter.getValue());
        }
        DBCursor dbc = targetActions.find(queryDoc,
                MongoUtil.createDoc(EVENT_ACTION, 1, FIELD_TOTAL, 1, ACTION_TARGET, 1));
        if (query.getMaxResults() != null) {
            dbc.limit(query.getMaxResults());
        }
        DBObject resultAction, resultTargets, resultTarget;
        String actionName;
        Long count;
        StatAction action;
        while (dbc.hasNext()) {
            resultAction = dbc.next();
            actionName = String.valueOf(resultAction.get(EVENT_ACTION));
            count = ((Number) resultAction.get(FIELD_TOTAL)).longValue();
            action = new StatAction(actionName, count);
            actions.add(action);
            //Add targets
            resultTargets = (DBObject) resultAction.get(ACTION_TARGET);
            for (String targetName : resultTargets.keySet()) {
                resultTarget = (DBObject) resultTargets.get(targetName);
                count = ((Number) resultTarget.get(FIELD_COUNT)).longValue();
                action.getTargets().add(new StatCounter(targetName, count));
            }
        }
    } catch (Exception ex) {
        log.error("getActions", ex);
        throw new StatsEngineException("getActions", ex);
    }
    return actions;
}

From source file:org.mule.module.mongo.api.MongoClientImpl.java

License:Open Source License

@Override
public Iterable<DBObject> findObjects(@NotNull final String collection, final DBObject query,
        final List<String> fields, final Integer numToSkip, final Integer limit, DBObject sortBy) {
    Validate.notNull(collection);/*from   w  w  w  .j av  a2 s  .  c om*/

    DBCursor dbCursor = db.getCollection(collection).find(query, FieldsSet.from(fields));
    if (numToSkip != null) {
        dbCursor = dbCursor.skip(numToSkip);
    }
    if (limit != null) {
        dbCursor = dbCursor.limit(limit);
    }
    if (sortBy != null) {
        dbCursor.sort(sortBy);
    }

    return bug5588Workaround(dbCursor);
}

From source file:org.s1.mongodb.MongoDBQueryHelper.java

License:Apache License

/**
 *
 * @param c// ww  w .  j a  v  a2  s. c om
 * @param search
 * @param sort
 * @param fields
 * @param skip
 * @param max
 * @return
 */
public static List<Map<String, Object>> list(CollectionId c, Map<String, Object> search,
        Map<String, Object> sort, Map<String, Object> fields, int skip, int max) {
    List<Map<String, Object>> res = Objects.newArrayList();
    DBCollection coll = MongoDBConnectionHelper.getCollection(c);

    if (search == null)
        search = Objects.newHashMap();

    DBCursor cur = coll.find(MongoDBFormat.fromMap(search), MongoDBFormat.fromMap(fields));
    if (max > 0)
        cur.limit(max);
    if (skip >= 0)
        cur.skip(skip);

    if (sort != null) {
        cur = cur.sort(MongoDBFormat.fromMap(sort));
    }

    while (cur.hasNext()) {
        DBObject obj = cur.next();

        Map<String, Object> m = MongoDBFormat.toMap(obj);

        res.add(m);
    }

    if (LOG.isDebugEnabled())
        LOG.debug("MongoDB list result (" + c + ", search:" + search + ", sort:" + sort + ", fields:" + fields
                + ", max:" + max + ", skip:" + skip + "\n\t> " + res);

    return res;
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

public <T> List<T> find(String collectionName, final Query query, Class<T> targetClass) {
    CursorPreparer cursorPreparer = null;
    if (query.getSkip() > 0 || query.getLimit() > 0 || query.getSortObject() != null) {
        cursorPreparer = new CursorPreparer() {

            public DBCursor prepare(DBCursor cursor) {
                DBCursor cursorToUse = cursor;
                try {
                    if (query.getSkip() > 0) {
                        cursorToUse = cursorToUse.skip(query.getSkip());
                    }//  ww  w.j av  a2 s . co m
                    if (query.getLimit() > 0) {
                        cursorToUse = cursorToUse.limit(query.getLimit());
                    }
                    if (query.getSortObject() != null) {
                        cursorToUse = cursorToUse.sort(query.getSortObject());
                    }
                } catch (RuntimeException e) {
                    throw potentiallyConvertRuntimeException(e);
                }
                return cursorToUse;
            }
        };
    }
    return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, cursorPreparer);
}

From source file:org.springframework.datastore.mapping.mongo.query.MongoQuery.java

License:Apache License

@Override
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @Override//from   w w w.  j a  v  a 2 s .c  o  m
        public List doInDB(DB db) throws MongoException, DataAccessException {

            final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
            if (uniqueResult) {
                final DBObject dbObject;
                if (criteria.isEmpty()) {
                    if (entity.isRoot()) {
                        dbObject = collection.findOne();
                    } else {
                        DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator());
                        dbObject = collection.findOne(query);
                    }
                } else {
                    DBObject query = getMongoQuery();

                    dbObject = collection.findOne(query);
                }
                final Object object = createObjectFromDBObject(dbObject);
                return wrapObjectResultInList(object);
            } else {
                DBCursor cursor;
                DBObject query = createQueryObject(entity);

                final List<Projection> projectionList = projections().getProjectionList();
                if (projectionList.isEmpty()) {
                    cursor = executeQuery(entity, criteria, collection, query);
                    return new MongoResultList(cursor, mongoEntityPersister);
                } else {
                    List projectedResults = new ArrayList();
                    for (Projection projection : projectionList) {
                        if (projection instanceof CountProjection) {
                            // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
                            //projectedResults.add(collection.getCount(query));
                            cursor = executeQuery(entity, criteria, collection, query);
                            projectedResults.add(cursor.size());
                        } else if (projection instanceof MinProjection) {
                            cursor = executeQuery(entity, criteria, collection, query);
                            MinProjection mp = (MinProjection) projection;

                            MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                            projectedResults.add(
                                    manualProjections.min((Collection) results.clone(), mp.getPropertyName()));
                        } else if (projection instanceof MaxProjection) {
                            cursor = executeQuery(entity, criteria, collection, query);
                            MaxProjection mp = (MaxProjection) projection;

                            MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                            projectedResults.add(
                                    manualProjections.max((Collection) results.clone(), mp.getPropertyName()));
                        } else if ((projection instanceof PropertyProjection)
                                || (projection instanceof IdProjection)) {
                            final PersistentProperty persistentProperty;
                            final String propertyName;
                            if (projection instanceof IdProjection) {
                                persistentProperty = entity.getIdentity();
                                propertyName = MongoEntityPersister.MONGO_ID_FIELD;
                            } else {
                                PropertyProjection pp = (PropertyProjection) projection;
                                persistentProperty = entity.getPropertyByName(pp.getPropertyName());
                                propertyName = pp.getPropertyName();
                            }
                            if (persistentProperty != null) {
                                populateMongoQuery(entity, query, criteria);
                                List propertyResults = collection.distinct(propertyName, query);

                                if (persistentProperty instanceof ToOne) {
                                    Association a = (Association) persistentProperty;
                                    propertyResults = session.retrieveAll(
                                            a.getAssociatedEntity().getJavaClass(), propertyResults);
                                }

                                if (projectedResults.size() == 0 && projectionList.size() == 1) {
                                    return propertyResults;
                                } else {
                                    projectedResults.add(propertyResults);
                                }
                            } else {
                                throw new InvalidDataAccessResourceUsageException(
                                        "Cannot use [" + projection.getClass().getSimpleName()
                                                + "] projection on non-existent property: " + propertyName);
                            }
                        }
                    }

                    return projectedResults;
                }

            }
        }

        protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria,
                final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            if (criteria.isEmpty()) {
                cursor = executeQueryAndApplyPagination(collection, query);
            } else {

                populateMongoQuery(entity, query, criteria);

                cursor = executeQueryAndApplyPagination(collection, query);

            }
            return cursor;
        }

        protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            cursor = collection.find(query);
            if (offset > 0) {
                cursor.skip(offset);
            }
            if (max > -1) {
                cursor.limit(max);
            }

            for (Order order : orderBy) {
                DBObject orderObject = new BasicDBObject();
                orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1);
                cursor.sort(orderObject);
            }

            return cursor;
        }

    });
}

From source file:org.vertx.java.busmods.persistor.MongoPersistor.java

License:Apache License

private void doFind(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;//www.j a  v  a 2 s. co m
    }
    Integer limit = (Integer) message.body.getNumber("limit");
    if (limit == null) {
        limit = -1;
    }
    Integer batchSize = (Integer) message.body.getNumber("batch_size");
    if (batchSize == null) {
        batchSize = 100;
    }
    JsonObject matcher = getMandatoryObject("matcher", message);
    if (matcher == null) {
        return;
    }
    JsonObject sort = message.body.getObject("sort");
    DBCollection coll = db.getCollection(collection);
    DBCursor cursor = coll.find(jsonToDBObject(matcher));
    if (limit != -1) {
        cursor.limit(limit);
    }
    if (sort != null) {
        cursor.sort(jsonToDBObject(sort));
    }
    sendBatch(message, cursor, batchSize);
}

From source file:org.vertx.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  va  2 s .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;
    }
    JsonObject matcher = getMandatoryObject("matcher", message);
    if (matcher == null) {
        return;
    }
    JsonObject keys = message.body.getObject("keys");

    Object sort = message.body.getField("sort");
    DBCollection coll = db.getCollection(collection);
    DBCursor cursor = (keys == null) ? coll.find(jsonToDBObject(matcher))
            : coll.find(jsonToDBObject(matcher), jsonToDBObject(keys));
    if (skip != -1) {
        cursor.skip(skip);
    }
    if (limit != -1) {
        cursor.limit(limit);
    }
    if (sort != null) {
        cursor.sort(sortObjectToDBObject(sort));
    }
    sendBatch(message, cursor, batchSize);
}

From source file:org.wikidata.couchbase.MongoPersistHandler.java

License:Open Source License

@Override
public List<DBObject> load(int start, int limit) {
    DBCursor cursor = getCollection().find();
    cursor.skip(start);/*from   ww w .ja  v a 2  s .c o m*/
    cursor.limit(limit);
    List<DBObject> result = new LinkedList<DBObject>();
    try {
        while (cursor.hasNext()) {
            result.add(cursor.next());
        }
    } finally {
        cursor.close();
    }
    return result;
}

From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java

License:Apache License

@Override
public Set<Model> search(final SearchCriteria searchCriteria) throws UnsupportedOperationException {

    // Identify the mongo collection to query.
    final Dimensions resultDimensions = searchCriteria.getResultDimensions();

    final URI schemaUri = resultDimensions.getSchemaUri();
    final String collectionName = convertToCollectionName(schemaUri);
    if (!_Mongo.collectionExists(collectionName)) {
        LOG.debug(getConfiguration().getName() + " - Collection does not exist. Name:\n" + collectionName);
        return null;
    }// w ww  . j  av a2s  .  com

    final DBCollection mongoCollection = _Mongo.getCollection(collectionName);
    if (mongoCollection == null) {
        // Should not happen
        LOG.error(getConfiguration().getName() + " - Collection should exist. Name:\n" + collectionName);
        return null;
    }

    // Build the mongo query object.
    final DBObject mongoQuery = createMongoQuery(searchCriteria);
    if (mongoQuery == null) {
        LOG.warn(getConfiguration().getName() + " - Query could not be created for: " + searchCriteria);
        return null;
    }

    // Build the mongo projection (fields to return).
    DBObject mongoKeys = null;
    final Set<String> projectionSlotNames = searchCriteria.getProjectionSlotNames();
    if (projectionSlotNames != null && !projectionSlotNames.isEmpty()) {
        for (final String projectionSlotName : projectionSlotNames) {
            mongoKeys.put(projectionSlotName, 1);
        }
    }

    // Query mongo
    final DBCursor cursor = mongoCollection.find(mongoQuery, mongoKeys);
    final int resultLimit = searchCriteria.getResultLimit();

    if (resultLimit > 0) {
        cursor.limit(resultLimit);
    }

    // TODO: Support skipping to an offset
    //cursor.skip(offset);

    // Build model results
    final Set<Model> resultSet = new LinkedHashSet<>();

    try {
        while (cursor.hasNext()) {
            final DBObject mongoObject = cursor.next();
            final Model model;

            try {
                model = convertToModel(mongoObject, null, resultDimensions);
                // Note: Context will set URI value in Document models.
            } catch (ModelReadingException e) {
                LOG.error(e.getMessage(), e);
                continue;
            }

            resultSet.add(model);
        }
    } finally {
        cursor.close();
    }

    return resultSet;
}