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.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbFindAllAccessImpl.java

License:Apache License

@Override
public void performExecute() {
    List<T> foundResult = new ArrayList<T>();

    DBCursor cur = getDBCollection().find();

    if (orderBy != null) {
        cur.sort(new BasicDBObject(orderBy, orderByAsc ? 1 : -1));
    }//from ww w .j  a  va2 s.com

    if (firstResult >= 0) {
        cur.skip(firstResult);
    }
    if (maxResult >= 1) {
        cur.limit(maxResult);
    }

    for (DBObject each : cur) {
        T eachResult = getDataMapper().toDomain(each);
        foundResult.add(eachResult);
    }

    this.result = foundResult;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbFindByConditionAccessImpl.java

License:Apache License

@Override
public void performExecute() {

    DBObject query = createQuery();/*from w  w w.ja  v  a  2  s  .c  om*/

    DBCursor cur = getDBCollection().find(query);
    sort(cur);

    if (firstResult >= 0) {
        cur.skip(firstResult);
    }
    if (maxResult >= 1) {
        cur.limit(maxResult);
    }

    List<T> foundResult = new ArrayList<T>();
    for (DBObject each : cur) {
        T eachResult = getDataMapper().toDomain(each);
        foundResult.add(eachResult);
    }

    this.result = foundResult;

}

From source file:org.fracturedatlas.athena.apa.impl.MongoApaAdapter.java

License:Open Source License

private DBCursor setLimit(DBCursor recordsCursor, String limit) {
    if (limit != null) {
        try {/*from w ww  .  ja va 2s  .c o  m*/
            Integer lim = Integer.parseInt(limit);
            recordsCursor.limit(lim);
        } catch (NumberFormatException nfe) {
            //ignored, no limit will be set
        }
    }

    return recordsCursor;
}

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

License:Apache License

@SuppressWarnings("hiding")
@Override/* w w  w  . jav  a2 s . c  om*/
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @SuppressWarnings("unchecked")
        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 = collection.findOne(new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator()));
                    }
                } else {
                    dbObject = collection.findOne(getMongoQuery());
                }
                return wrapObjectResultInList(createObjectFromDBObject(dbObject));
            }

            DBCursor cursor = null;
            DBObject query = createQueryObject(entity);

            final List<Projection> projectionList = projections().getProjectionList();
            if (projectionList.isEmpty()) {
                cursor = executeQuery(entity, criteria, collection, query);
                return (List) new MongoResultList(cursor, mongoEntityPersister).clone();
            }

            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));
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    projectedResults.add(cursor.size());
                } else if (projection instanceof MinProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MinProjection mp = (MinProjection) projection;

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

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

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.countDistinct((Collection) results.clone(),
                            getPropertyName(entity, 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 = getPropertyName(entity, persistentProperty.getName());
                    }
                    if (persistentProperty != null) {
                        populateMongoQuery(entity, query, criteria);

                        List propertyResults = null;
                        if (max > -1) {
                            // if there is a limit then we have to do a manual projection since the MongoDB driver doesn't support limits and distinct together
                            cursor = executeQueryAndApplyPagination(collection, query);
                            propertyResults = manualProjections
                                    .property(new MongoResultList(cursor, mongoEntityPersister), propertyName);
                        } else {

                            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;
                        }
                        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);
            }

            if (queryArguments != null) {
                if (queryArguments.containsKey(HINT_ARGUMENT)) {
                    Object hint = queryArguments.get(HINT_ARGUMENT);
                    if (hint instanceof Map) {
                        cursor.hint(new BasicDBObject((Map) hint));
                    } else if (hint != null) {
                        cursor.hint(hint.toString());
                    }

                }
            }
            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);
            }

            if (!orderBy.isEmpty()) {
                DBObject orderObject = new BasicDBObject();
                for (Order order : orderBy) {
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                }
                cursor.sort(orderObject);
            } else {
                MongoCollection coll = (MongoCollection) entity.getMapping().getMappedForm();
                if (coll != null && coll.getSort() != null) {
                    DBObject orderObject = new BasicDBObject();
                    Order order = coll.getSort();
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                    cursor.sort(orderObject);
                }

            }

            return cursor;
        }
    });
}

From source file:org.hibernate.ogm.datastore.mongodb.MongoDBDialect.java

License:LGPL

private ClosableIterator<Tuple> doFind(MongoDBQueryDescriptor query, QueryParameters queryParameters,
        DBCollection collection, EntityKeyMetadata entityKeyMetadata) {
    DBCursor cursor = collection.find(query.getCriteria(), query.getProjection());

    if (query.getOrderBy() != null) {
        cursor.sort(query.getOrderBy());
    }//from   w  ww.  jav a2s. co m

    // apply firstRow/maxRows if present
    if (queryParameters.getRowSelection().getFirstRow() != null) {
        cursor.skip(queryParameters.getRowSelection().getFirstRow());
    }

    if (queryParameters.getRowSelection().getMaxRows() != null) {
        cursor.limit(queryParameters.getRowSelection().getMaxRows());
    }

    return new MongoDBResultsCursor(cursor, entityKeyMetadata);
}

From source file:org.iternine.jeppetto.dao.mongodb.BasicDBObjectCommand.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//from ww w . ja v  a  2  s.co  m
public Object singleResult(DBCollection dbCollection) throws NoSuchItemException {
    DBCursor cursor = cursor(dbCollection);
    cursor.limit(2);

    if (!cursor.hasNext()) {
        throw new NoSuchItemException(dbCollection.getName(), query.toString());
    }

    Object result = cursor.next();

    if (cursor.hasNext()) {
        throw new RuntimeException("More than one " + dbCollection.getName() + " matches query: " + query);
    }

    ((DirtyableDBObject) result).markPersisted();

    return result;
}

From source file:org.iternine.jeppetto.dao.mongodb.MongoDBQueryModelDAO.java

License:Apache License

public Iterable<T> findUsingQueryModel(QueryModel queryModel) {
    MongoDBCommand command = buildCommand(queryModel);
    DBCursor dbCursor = command.cursor(dbCollection);

    if (queryModel.getSorts() != null) {
        dbCursor.sort(processSorts(queryModel.getSorts()));
    }/*from  w  w w.ja  va 2 s  .  com*/

    if (queryModel.getFirstResult() > 0) {
        dbCursor = dbCursor.skip(queryModel.getFirstResult()); // dbCursor is zero-indexed, firstResult is one-indexed
    }

    if (queryModel.getMaxResults() > 0) {
        dbCursor = dbCursor.limit(queryModel.getMaxResults());
    }

    final DBCursor finalDbCursor = dbCursor;

    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                @Override
                public boolean hasNext() {
                    return finalDbCursor.hasNext();
                }

                @Override
                @SuppressWarnings({ "unchecked" })
                public T next() {
                    DBObject result = finalDbCursor.next();

                    ((DirtyableDBObject) result).markPersisted();

                    if (MongoDBSession.isActive()) {
                        MongoDBSession.trackForSave(MongoDBQueryModelDAO.this, buildIdentifyingQuery(result),
                                (T) result, createIdentifyingQueries(result));
                    }

                    return (T) result;
                }

                @Override
                public void remove() {
                    finalDbCursor.remove();
                }
            };
        }
    };
}

From source file:org.jeo.mongo.MongoDataset.java

License:Open Source License

@Override
public Cursor<Feature> cursor(Query q) throws IOException {
    if (q.getMode() == Mode.APPEND) {
        return new MongoCursor(q.getMode(), null, this);
    }//from  w  ww .  jav a  2  s  .com

    QueryPlan qp = new QueryPlan(q);

    //TODO: sorting
    DBCursor dbCursor = !Envelopes.isNull(q.getBounds()) ? dbcol.find(encodeBboxQuery(q.getBounds()))
            : dbcol.find();
    qp.bounded();

    Integer offset = q.getOffset();
    if (offset != null) {
        dbCursor.skip(offset);
        qp.offsetted();
    }

    Integer limit = q.getLimit();
    if (limit != null) {
        dbCursor.limit(limit);
        qp.limited();
    }

    return qp.apply(new MongoCursor(q.getMode(), dbCursor, this));
}

From source file:org.jewzaam.mongo.command.MongoFindCommand.java

License:Open Source License

@Override
protected MongoIterator<T> run() {
    DBCollection coll = db.getCollection(collectionName);

    DBObject query = null;//from   w  w w.  j  av  a2s  .c  o m
    if (search instanceof DBObject) {
        query = (DBObject) search;
    } else if (null != search) {
        jsonQuery = converter.toJson(search);
    }

    if (query == null) {
        query = (DBObject) JSON.parse(jsonQuery);
    }

    DBObject projection = null;

    if (jsonProjection != null) {
        projection = (DBObject) JSON.parse(jsonProjection);
    }

    DBCursor cur = coll.find(query, projection);
    if (limit >= 0) {
        cur = cur.limit(limit);
    }

    return new MongoIterator<>(cur, clazz);
}

From source file:org.jongo.Find.java

License:Apache License

public Find limit(final int limit) {
    this.modifiers.add(new QueryModifier() {
        public void modify(DBCursor cursor) {
            cursor.limit(limit);
        }/*from  w  w w  .j  a v  a 2  s  .  c  o m*/
    });
    return this;
}