List of usage examples for com.mongodb DBCursor sort
public DBCursor sort(final DBObject orderBy)
From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbFindByConditionAccessImpl.java
License:Apache License
protected void sort(DBCursor cur) { BasicDBObject orderBy = new BasicDBObject(); for (ConditionalCriteria crit : cndCriterias) { if (Operator.OrderAsc.equals(crit.getOperator())) { orderBy.put(crit.getPropertyFullName(), 1); } else if (Operator.OrderDesc.equals(crit.getOperator())) { orderBy.put(crit.getPropertyFullName(), -1); }/*from ww w. j av a 2 s . c o m*/ } if (!orderBy.isEmpty()) { cur.sort(orderBy); } }
From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java
License:Apache License
@SuppressWarnings("hiding") @Override/* www . ja v a 2s . co m*/ 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()); }/* www. j a v a2 s . 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.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())); }/* w w w . j a v a2s . c om*/ 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.jberet.repository.MongoRepository.java
License:Open Source License
@Override public List<JobExecution> getJobExecutions(final JobInstance jobInstance) { long jobInstanceId = jobInstance == null ? 0 : jobInstance.getInstanceId(); DBCursor cursor = jobInstance == null ? db.getCollection(TableColumns.JOB_EXECUTION).find() : db.getCollection(TableColumns.JOB_EXECUTION) .find(new BasicDBObject(TableColumns.JOBINSTANCEID, jobInstance.getInstanceId())); cursor = cursor.sort(new BasicDBObject(TableColumns.JOBEXECUTIONID, 1)); final List<JobExecution> result = new ArrayList<JobExecution>(); while (cursor.hasNext()) { final DBObject next = cursor.next(); final Long i = (Long) next.get(TableColumns.JOBEXECUTIONID); final SoftReference<JobExecutionImpl, Long> ref = jobExecutions.get(i); JobExecutionImpl jobExecution1 = (ref != null) ? ref.get() : null; if (jobExecution1 == null) { if (jobInstance == null) { jobInstanceId = (Long) next.get(TableColumns.JOBINSTANCEID); }/*from ww w . jav a 2 s .c om*/ final Properties jobParameters1 = BatchUtil .stringToProperties((String) next.get(TableColumns.JOBPARAMETERS)); jobExecution1 = new JobExecutionImpl(getJobInstance(jobInstanceId), i, jobParameters1, (Date) next.get(TableColumns.CREATETIME), (Date) next.get(TableColumns.STARTTIME), (Date) next.get(TableColumns.ENDTIME), (Date) next.get(TableColumns.LASTUPDATEDTIME), (String) next.get(TableColumns.BATCHSTATUS), (String) next.get(TableColumns.EXITSTATUS), (String) next.get(TableColumns.RESTARTPOSITION)); jobExecutions.put(i, new SoftReference<JobExecutionImpl, Long>(jobExecution1, jobExecutionReferenceQueue, i)); } // jobExecution1 is either got from the cache, or created, now add it to the result list result.add(jobExecution1); } return result; }
From source file:org.jberet.repository.MongoRepository.java
License:Open Source License
/** * Retrieves a list of StepExecution from database by JobExecution id. This method does not check the cache, so it * should only be called after the cache has been searched without a match. * * @param jobExecutionId if null, retrieves all StepExecutions; otherwise, retrieves all StepExecutions belongs to the JobExecution id * @return a list of StepExecutions//from w ww . ja va 2 s .c o m */ @Override List<StepExecution> selectStepExecutions(final Long jobExecutionId, final ClassLoader classLoader) { final DBCollection collection = db.getCollection(TableColumns.STEP_EXECUTION); DBCursor cursor = jobExecutionId == null ? collection.find() : collection.find(new BasicDBObject(TableColumns.JOBEXECUTIONID, jobExecutionId)); cursor = cursor.sort(new BasicDBObject(TableColumns.STEPEXECUTIONID, 1)); final List<StepExecution> result = new ArrayList<StepExecution>(); createStepExecutionsFromDBCursor(cursor, result, classLoader); return result; }
From source file:org.jongo.Find.java
License:Apache License
public Find sort(String sort) { final DBObject sortDBObject = queryFactory.createQuery(sort).toDBObject(); this.modifiers.add(new QueryModifier() { public void modify(DBCursor cursor) { cursor.sort(sortDBObject); }/*ww w .jav a 2s . c om*/ }); return this; }
From source file:org.mephi.griffin.actorcloud.storage.StorageActor.java
License:Apache License
@Override public void onReceive(Object message) { logger.entering("StorageActor", "onReceive"); if (message instanceof Get) { logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageActor <- Get from " + getSender().path().name() + ": " + message); Get request = (Get) message;/*from w w w . jav a 2 s .co m*/ DBCursor cursor; StorageResult msg; try { if (request.getQuery() != null) cursor = db.getCollection(request.getCollection()).find(request.getQuery()); else cursor = db.getCollection(request.getCollection()).find(); if (request.getSort() != null) cursor = cursor.sort(request.getSort()); Entity[] result = new Entity[cursor.size()]; int i = 0; while (cursor.hasNext()) { BasicDBObject tmp = (BasicDBObject) cursor.next(); result[i++] = new Entity(tmp); } msg = new StorageResult(StorageResult.GET, request.getId(), result); } catch (MongoException me) { logger.throwing("StorageActor", "onReceive", me); msg = new StorageResult(StorageResult.GET, request.getId(), me.getMessage()); } logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageResult -> " + getSender().path().name() + ": " + msg); getSender().tell(msg, getSelf()); } else if (message instanceof Insert) { logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageActor <- Insert from " + getSender().path().name() + ": " + message); Insert request = (Insert) message; StorageResult msg; try { WriteResult result = db.getCollection(request.getCollection()).insert(request.getDocs()); msg = new StorageResult(StorageResult.PUT, request.getId(), result.getN()); } catch (MongoException me) { logger.throwing("StorageActor", "onReceive", me); msg = new StorageResult(StorageResult.PUT, request.getId(), me.getMessage()); } logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageResult -> " + getSender().path().name() + ": " + msg); getSender().tell(msg, getSelf()); } else if (message instanceof Update) { logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageActor <- Update from " + getSender().path().name() + ": " + message); Update request = (Update) message; StorageResult msg; try { WriteResult result = db.getCollection(request.getCollection()).update(request.getQuery(), new BasicDBObject("$set", request.getFields())); msg = new StorageResult(StorageResult.UPDATE, request.getId(), result.getN()); } catch (MongoException me) { logger.throwing("StorageActor", "onReceive", me); msg = new StorageResult(StorageResult.UPDATE, request.getId(), me.getMessage()); } logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageResult -> " + getSender().path().name() + ": " + msg); getSender().tell(msg, getSelf()); } else if (message instanceof Remove) { logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageActor <- Remove from " + getSender().path().name() + ": " + message); Remove request = (Remove) message; StorageResult msg; try { WriteResult result = db.getCollection(request.getCollection()).remove(request.getQuery()); msg = new StorageResult(StorageResult.REMOVE, request.getId(), result.getN()); } catch (MongoException me) { logger.throwing("StorageActor", "onReceive", me); msg = new StorageResult(StorageResult.REMOVE, request.getId(), me.getMessage()); } logger.logp(Level.FINER, "StorageActor", "onReceive", "StorageResult -> " + getSender().path().name() + ": " + msg); getSender().tell(msg, getSelf()); } else unhandled(message); logger.exiting("StorageActor", "onReceive"); }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
@Override public List<StatCounter> getTopTargets(Query query) throws StatsEngineException { List<StatCounter> result = new ArrayList<StatCounter>(); try {/*w ww . j ava 2 s.c o m*/ DBCollection counters = getCounterCollection(); DBObject queryDoc = MongoUtil.createDoc(EVENT_CLIENT_ID, getQueryValue(query, QueryField.CLIENT_ID), EVENT_TARGET_TYPE, getQueryValue(query, QueryField.TARGET_TYPE)); String actionCountPath = createDotPath(EVENT_ACTION, getQueryValue(query, QueryField.ACTION), FIELD_COUNT); DBObject order = MongoUtil.createDoc(actionCountPath, getQueryOrder(query)); log.debug("Ensuring index for {}", order); counters.ensureIndex(order); log.debug("Querying counters"); DBCursor dbc = counters.find(queryDoc, MongoUtil.createDoc(EVENT_TARGET, 1, EVENT_ACTION, 1)); Integer limit = query.getMaxResults(); dbc = dbc.sort(order).limit(limit == null ? 10 : limit); BasicDBObject counter; String target; Long count; while (dbc.hasNext()) { counter = (BasicDBObject) dbc.next(); target = String.valueOf(counter.get(EVENT_TARGET)); count = MongoUtil.getChildDBObject(counter, actionCountPath, 2).getLong(FIELD_COUNT); result.add(new StatCounter(target, count)); } } catch (Exception ex) { log.error("getTopTargets", ex); throw new StatsEngineException("getTopTargets", ex); } return result; }
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 a va 2 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); }