List of usage examples for com.mongodb DBCursor sort
public DBCursor sort(final DBObject orderBy)
From source file:org.broad.igv.plugin.mongocollab.MongoFeatureSource.java
License:Open Source License
/** * * @param queryObject/*from w w w.j a v a 2 s . co m*/ * @param limit Limitation on the number of results returned. Setting to 0 is equivalent to unlimited * @return * @throws IOException */ private Collection<DBFeature.IGVFeat> getFeatures(DBObject queryObject, int limit) throws IOException { DBCursor cursor = this.collection.find(queryObject); cursor.limit(limit >= 0 ? limit : 0); //Sort by increasing start value //Only do this if we have an index, otherwise might be too memory intensive if (hasLocusIndex) { cursor.sort(new BasicDBObject("Start", 1)); } boolean isSorted = true; int lastStart = -1; List<DBFeature.IGVFeat> features = new ArrayList<DBFeature.IGVFeat>(); while (cursor.hasNext()) { DBObject obj = cursor.next(); DBFeature feat = (DBFeature) obj; features.add(feat.createIGVFeature()); isSorted &= feat.getStart() >= lastStart; lastStart = feat.getStart(); } if (!isSorted) { FeatureUtils.sortFeatureList(features); } return features; }
From source file:org.canedata.provider.mongodb.entity.MongoEntity.java
License:Apache License
public List<Fields> list(int offset, int count) { if (logger.isDebug()) logger.debug("Listing entities, Database is {0}, Collection is {1}, offset is {2}, count is {3}.", getSchema(), getName(), offset, count); List<Fields> rlt = new ArrayList<Fields>(); BasicDBObject options = new BasicDBObject(); DBCursor cursor = null; try {/*from w ww.ja v a 2 s . c o m*/ validateState(); MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl(); BasicDBObject projection = new BasicDBObject(); Limiter limiter = new Limiter.Default(); BasicDBObject sorter = new BasicDBObject(); IntentParser.parse(getIntent(), expFactory, null, projection, limiter, sorter, options); if (!options.isEmpty()) prepareOptions(options); if (null != getCache()) {// cache cursor = getCollection().find(expFactory.toQuery(), new BasicDBObject().append("_id", 1)); } else {// no cache // projection if (projection.isEmpty()) cursor = getCollection().find(expFactory.toQuery()); else cursor = getCollection().find(expFactory.toQuery(), projection); } // sort if (!sorter.isEmpty()) cursor.sort(sorter); if (offset > 0) limiter.offset(offset); if (count > 0) limiter.count(count); if (limiter.offset() > 0) cursor.skip(limiter.offset()); if (limiter.count() > 0) cursor.limit(limiter.count()); if (null != getCache()) { Map<Object, MongoFields> missedCacheHits = new HashMap<Object, MongoFields>(); while (cursor.hasNext()) { BasicDBObject dbo = (BasicDBObject) cursor.next(); Object key = dbo.get("_id"); String cacheKey = getKey().concat("#").concat(key.toString()); MongoFields ele = null; if (getCache().isAlive(cacheKey)) {// load from cache MongoFields mf = (MongoFields) getCache().restore(cacheKey); if (null != mf) ele = mf.clone();// pooling } if (null != ele && !projection.isEmpty()) ele.project(projection.keySet()); if (null == ele) { ele = new MongoFields(this, getIntent()); missedCacheHits.put(key, ele); } rlt.add(ele); } // load missed cache hits. if (!missedCacheHits.isEmpty()) { loadForMissedCacheHits(missedCacheHits, projection.keySet()); missedCacheHits.clear(); } if (logger.isDebug()) logger.debug("Listed entities hit cache ..."); } else { while (cursor.hasNext()) { BasicDBObject dbo = (BasicDBObject) cursor.next(); rlt.add(new MongoFields(this, getIntent(), dbo)); } if (logger.isDebug()) logger.debug("Listed entities ..."); } return rlt; } catch (AnalyzeBehaviourException abe) { if (logger.isDebug()) logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage()); throw new RuntimeException(abe); } finally { if (!options.getBoolean(Options.RETAIN)) getIntent().reset(); if (cursor != null) cursor.close(); } }
From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java
License:Apache License
private MongoCollectionResult find(MongoQueryOptions mongoQueryOptions, MongoCollectionResult mongoCollectionResult, DBCollection collection) { DBObject filter = mongoQueryOptions.getFilter(); DBObject projection = mongoQueryOptions.getProjection(); DBObject sort = mongoQueryOptions.getSort(); DBCursor cursor; if (projection == null) { cursor = collection.find(filter); } else {/* w w w .j av a 2 s .co m*/ cursor = collection.find(filter, projection); } if (sort != null) { cursor = cursor.sort(sort); } try { int index = 0; while (cursor.hasNext() && index < mongoQueryOptions.getResultLimit()) { mongoCollectionResult.add(cursor.next()); index++; } } finally { cursor.close(); } return mongoCollectionResult; }
From source file:org.codinjutsu.tools.nosql.mongo.logic.MongoClient.java
License:Apache License
private MongoResult find(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult, DBCollection collection) {/*www. j a v a 2 s .c o m*/ DBObject filter = mongoQueryOptions.getFilter(); DBObject projection = mongoQueryOptions.getProjection(); DBObject sort = mongoQueryOptions.getSort(); DBCursor cursor; if (projection == null) { cursor = collection.find(filter); } else { cursor = collection.find(filter, projection); } if (sort != null) { cursor = cursor.sort(sort); } try { int index = 0; while (cursor.hasNext() && index < mongoQueryOptions.getResultLimit()) { mongoResult.add(cursor.next()); index++; } } finally { cursor.close(); } return mongoResult; }
From source file:org.datanucleus.store.mongodb.MongoDBUtils.java
License:Open Source License
/** * Convenience method to return all objects of the candidate type (optionally allowing subclasses). * @param q Query/*from w w w.j a v a 2s . com*/ * @param db Mongo DB * @param filterObject Optional filter object * @param orderingObject Optional ordering object * @param options Set of options for controlling this query * @param skip Number of records to skip * @param limit Max number of records to return * @return List of all candidate objects (implements QueryResult) */ public static List getObjectsOfCandidateType(Query q, DB db, BasicDBObject filterObject, BasicDBObject orderingObject, Map<String, Object> options, Integer skip, Integer limit) { LazyLoadQueryResult qr = new LazyLoadQueryResult(q); // Find the DBCollections we need to query ExecutionContext ec = q.getExecutionContext(); StoreManager storeMgr = ec.getStoreManager(); ClassLoaderResolver clr = ec.getClassLoaderResolver(); List<AbstractClassMetaData> cmds = MetaDataUtils.getMetaDataForCandidates(q.getCandidateClass(), q.isSubclasses(), ec); Map<String, List<AbstractClassMetaData>> classesByCollectionName = new HashMap(); for (AbstractClassMetaData cmd : cmds) { if (cmd instanceof ClassMetaData && ((ClassMetaData) cmd).isAbstract()) { // Omit any classes that are not instantiable (e.g abstract) } else { String collectionName = storeMgr.getNamingFactory().getTableName(cmd); List<AbstractClassMetaData> cmdsForCollection = classesByCollectionName.get(collectionName); if (cmdsForCollection == null) { cmdsForCollection = new ArrayList(); classesByCollectionName.put(collectionName, cmdsForCollection); } cmdsForCollection.add(cmd); } } // Add a query for each DBCollection we need Iterator<Map.Entry<String, List<AbstractClassMetaData>>> iter = classesByCollectionName.entrySet() .iterator(); while (iter.hasNext()) { Map.Entry<String, List<AbstractClassMetaData>> entry = iter.next(); String collectionName = entry.getKey(); List<AbstractClassMetaData> cmdsForCollection = entry.getValue(); AbstractClassMetaData rootCmd = cmdsForCollection.get(0); int[] fpMembers = q.getFetchPlan().getFetchPlanForClass(rootCmd).getMemberNumbers(); BasicDBObject fieldsSelection = new BasicDBObject(); if (fpMembers != null && fpMembers.length > 0) { fieldsSelection = new BasicDBObject(); for (int i = 0; i < fpMembers.length; i++) { AbstractMemberMetaData mmd = rootCmd .getMetaDataForManagedMemberAtAbsolutePosition(fpMembers[i]); RelationType relationType = mmd.getRelationType(clr); if (mmd.isEmbedded() && RelationType.isRelationSingleValued(relationType)) { boolean nested = true; String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("false")) { nested = false; } if (nested) { // Nested Embedded field, so include field String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } else { // Flat Embedded field, so add all fields of sub-objects selectAllFieldsOfEmbeddedObject(mmd, fieldsSelection, ec, clr); } } else { String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } } } if (rootCmd.getIdentityType() == IdentityType.DATASTORE) { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DATASTOREID_COLUMN), 1); } if (rootCmd.isVersioned()) { VersionMetaData vermd = rootCmd.getVersionMetaDataForClass(); if (vermd.getFieldName() != null) { AbstractMemberMetaData verMmd = rootCmd.getMetaDataForMember(vermd.getFieldName()); String fieldName = storeMgr.getNamingFactory().getColumnName(verMmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } else { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.VERSION_COLUMN), 1); } } if (rootCmd.hasDiscriminatorStrategy()) { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN), 1); } BasicDBObject query = new BasicDBObject(); if (filterObject != null) { Iterator<Map.Entry<String, Object>> filterEntryIter = filterObject.entrySet().iterator(); while (filterEntryIter.hasNext()) { Map.Entry<String, Object> filterEntry = filterEntryIter.next(); query.put(filterEntry.getKey(), filterEntry.getValue()); } } if (rootCmd.hasDiscriminatorStrategy() && cmdsForCollection.size() == 1) { // TODO Add this restriction on *all* possible cmds for this DBCollection // Discriminator present : Add restriction on the discriminator value for this class query.put(storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN), rootCmd.getDiscriminatorValue()); } if (storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID) != null) { // Multitenancy discriminator present : Add restriction for this tenant if ("true".equalsIgnoreCase(rootCmd.getValueForExtension("multitenancy-disable"))) { // Don't bother with multitenancy for this class } else { String fieldName = storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.MULTITENANCY_COLUMN); String value = storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID); query.put(fieldName, value); } } DBCollection dbColl = db.getCollection(collectionName); Object val = (options != null ? options.get("slave-ok") : Boolean.FALSE); if (val == Boolean.TRUE) { dbColl.setReadPreference(ReadPreference.secondaryPreferred()); } if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE .debug("Performing find() using query on collection " + collectionName + " for fields=" + fieldsSelection + " with filter=" + query + " and ordering=" + orderingObject); } DBCursor curs = dbColl.find(query, fieldsSelection); if (ec.getStatistics() != null) { // Add to statistics ec.getStatistics().incrementNumReads(); } if (classesByCollectionName.size() == 1) { if (orderingObject != null) { curs = curs.sort(orderingObject); qr.setOrderProcessed(true); } // We have a single DBCursor so apply the range specification directly to this DBCursor if (skip != null && skip > 0) { curs = curs.skip(skip); qr.setRangeProcessed(true); } if (limit != null && limit > 0) { curs = curs.limit(limit); qr.setRangeProcessed(true); } } qr.addCandidateResult(rootCmd, curs, fpMembers); } return qr; }
From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java
License:Open Source License
/** * Applies data set query properties and hints on DBCursor, except * for cursor limit.//w w w . j ava 2s.c o m * @see #applyPropertiesToCursor(DBCursor,QueryProperties,boolean,boolean) */ static void applyPropertiesToCursor(DBCursor rowsCursor, QueryProperties queryProps, boolean includeSortExpr) { if (includeSortExpr) // normally done only when executing a query to get full result set { DBObject sortExprObj = null; try { sortExprObj = queryProps.getSortExprAsParsedObject(); } catch (OdaException ex) { // log warning and ignore DriverUtil.getLogger().log(Level.WARNING, Messages.bind("Unable to parse the user-defined Sort Expression: {0}", //$NON-NLS-1$ queryProps.getSortExpr()), ex); } if (sortExprObj != null) rowsCursor.sort(sortExprObj); } ReadPreference readPref = queryProps.getTaggableReadPreference(); if (readPref != null) rowsCursor.setReadPreference(readPref); if (queryProps.getBatchSize() > 0) rowsCursor.batchSize(queryProps.getBatchSize()); if (queryProps.getNumDocsToSkip() > 0) rowsCursor.skip(queryProps.getNumDocsToSkip()); DBObject hintObj = queryProps.getIndexHintsAsParsedObject(); if (hintObj != null) rowsCursor.hint(hintObj); else // try to pass the hint string value as is { String hintValue = queryProps.getIndexHints(); if (!hintValue.isEmpty()) rowsCursor.hint(hintValue); } if (queryProps.hasNoTimeOut()) rowsCursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT); if (queryProps.isPartialResultsOk()) rowsCursor.addOption(Bytes.QUERYOPTION_PARTIAL); }
From source file:org.eclipse.emf.cdo.server.internal.mongodb.MongoDBBrowserPage.java
License:Open Source License
protected void showDocuments(CDOServerBrowser browser, PrintStream pout, DBCollection coll) { DBCursor cursor = null; try {// ww w . j av a2 s .co m pout.print( "<tr><td colspan=\"2\" align=\"center\" bgcolor=\"EEEEEE\"><h4>Documents</h4></td></tr>\r\n"); int i = 0; cursor = coll.find(); try { cursor = cursor.sort(new BasicDBObject("_id", 1)); } catch (Exception ex) { // Ignore } while (cursor.hasNext()) { DBObject doc = cursor.next(); ++i; if (i == 1 && showFirstCommit(coll)) { continue; } String bg = (i & 1) == 1 ? "bgcolor=\"DDDDDD\"" : "bgcolor=\"EEEEEE\""; pout.print("<tr><td valign=\"top\" " + bg + "><b>" + i + " </b></td><td valign=\"top\">"); showObject(browser, pout, doc, ""); pout.print("</td></tr>\r\n"); } pout.print("</table>\r\n"); } finally { if (cursor != null) { cursor.close(); } } }
From source file:org.eclipselabs.mongoemf.streams.MongoInputStream.java
License:Open Source License
@Override public void loadResource(Resource resource) throws IOException { // We need to set up the XMLResource.URIHandler so that proxy URIs are handled properly. XMLResource.URIHandler uriHandler = (XMLResource.URIHandler) options.get(XMLResource.OPTION_URI_HANDLER); if (uriHandler == null) uriHandler = new org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl(); if (resource.getURI().hasQuery()) uriHandler.setBaseURI(resource.getURI().trimSegments(1).appendSegment("-1")); else/* w ww .j av a 2 s . c o m*/ uriHandler.setBaseURI(resource.getURI()); boolean includeAttributesForProxyReferences = Boolean.TRUE .equals(options.get(Options.OPTION_PROXY_ATTRIBUTES)); EObjectBuilder builder = builderFactory.createObjectBuilder(converterService, uriHandler, includeAttributesForProxyReferences, eClassCache); // If the URI contains a query string, use it to locate a collection of objects from // MongoDB, otherwise simply get the object from MongoDB using the id. EList<EObject> contents = resource.getContents(); if (uri.query() != null) { if (queryEngine == null) throw new IOException("The query engine was not found"); MongoQuery mongoQuery = queryEngine.buildDBObjectQuery(uri); DBCursor resultCursor = null; if (mongoQuery.getProjection() == null) resultCursor = collection.find(mongoQuery.getFilter()); else resultCursor = collection.find(mongoQuery.getFilter(), mongoQuery.getProjection()); if (mongoQuery.getSkip() != null) resultCursor.skip(mongoQuery.getSkip()); if (mongoQuery.getSort() != null) resultCursor = resultCursor.sort(mongoQuery.getSort()); if (mongoQuery.getLimit() != null) resultCursor = resultCursor.limit(mongoQuery.getLimit()); boolean createCursor = Boolean.TRUE.equals(options.get(Options.OPTION_QUERY_CURSOR)); if (createCursor) { MongoCursor cursor = ModelFactory.eINSTANCE.createMongoCursor(); cursor.setDbCollection(collection); cursor.setDbCursor(resultCursor); cursor.setObjectBuilder(builder); contents.add(cursor); } else { EReferenceCollection eCollection = EmodelingFactory.eINSTANCE.createEReferenceCollection(); InternalEList<EObject> values = (InternalEList<EObject>) eCollection.getValues(); for (DBObject dbObject : resultCursor) values.addUnique(builder.buildEObject(collection, dbObject, resource, true)); contents.add(eCollection); } } else { DBObject dbObject = collection.findOne(new BasicDBObject(Keywords.ID_KEY, MongoUtils.getID(uri))); if (dbObject != null) { EObject eObject = builder.buildEObject(collection, dbObject, resource, false); if (eObject != null) contents.add(eObject); response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, dbObject.get(Keywords.TIME_STAMP_KEY)); } } }
From source file:org.envirocar.server.mongo.dao.MongoMeasurementDao.java
License:Open Source License
private Measurements query(DBObject query, Pagination p) { final Mapper mapper = this.mongoDB.getMapper(); final Datastore ds = this.mongoDB.getDatastore(); final DBCollection coll = ds.getCollection(MongoMeasurement.class); DBCursor cursor = coll.find(query, null); long count = 0; cursor.setDecoderFactory(ds.getDecoderFact()); if (p != null) { count = coll.count(query);//from ww w . ja v a 2 s . c o m if (p.getOffset() > 0) { cursor.skip(p.getOffset()); } if (p.getLimit() > 0) { cursor.limit(p.getLimit()); } } cursor.sort(QueryImpl.parseFieldsString(MongoMeasurement.TIME, MongoMeasurement.class, mapper, true)); Iterable<MongoMeasurement> i = new MorphiaIterator<MongoMeasurement, MongoMeasurement>(cursor, mapper, MongoMeasurement.class, coll.getName(), mapper.createEntityCache()); return createPaginatedIterable(i, p, count); }
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 v a 2 s .c o m*/ 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; }