Java Code Examples for com.mongodb.client.FindIterable#skip()

The following examples show how to use com.mongodb.client.FindIterable#skip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PanacheQueryImpl.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void manageOffsets(FindIterable find, Integer limit) {
    if (range != null) {
        find.skip(range.getStartIndex());
        if (limit == null) {
            // range is 0 based, so we add 1 to the limit
            find.limit(range.getLastIndex() - range.getStartIndex() + 1);
        }
    } else if (page != null) {
        find.skip(page.index * page.size);
        if (limit == null) {
            find.limit(page.size);
        }
    }
    if (limit != null) {
        find.limit(limit);
    }
}
 
Example 2
Source File: MongoImpl.java    From tephra with MIT License 6 votes vote down vote up
@Override
public JSONArray find(String key, String collection, JSONObject where, int limit, int skip) {
    MongoCollection<Document> mc = getCollection(key, collection);
    if (mc == null)
        return new JSONArray();

    FindIterable<Document> fi = mc.find(toDocument(where));
    if (limit > 0)
        fi.limit(limit);
    if (skip > 0)
        fi.skip(skip);

    JSONArray array = new JSONArray();
    for (Document document : fi)
        array.add(JSON.parseObject(document.toJson()));

    return array;
}
 
Example 3
Source File: FindOptions.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * @param iterable the iterable to use
 * @param mapper   the mapper to use
 * @param type     the result type
 * @param <T>      the result type
 * @return the iterable instance for the query results
 * @morphia.internal
 */
public <T> FindIterable<T> apply(final FindIterable<T> iterable, final Mapper mapper, final Class<?> type) {
    if (projection != null) {
        iterable.projection(projection.map(mapper, type));
    }

    iterable.batchSize(batchSize);
    iterable.collation(collation);
    iterable.comment(comment);
    if (cursorType != null) {
        iterable.cursorType(cursorType);
    }
    iterable.hint(hint);
    iterable.hintString(hintString);
    iterable.limit(limit);
    iterable.max(max);
    iterable.maxAwaitTime(maxAwaitTimeMS, TimeUnit.MILLISECONDS);
    iterable.maxTime(maxTimeMS, TimeUnit.MILLISECONDS);
    iterable.min(min);
    iterable.noCursorTimeout(noCursorTimeout);
    iterable.oplogReplay(oplogReplay);
    iterable.partial(partial);
    iterable.returnKey(returnKey);
    iterable.showRecordId(showRecordId);
    iterable.skip(skip);
    if (sort != null) {
        Document mapped = new Document();
        MappedClass mappedClass = mapper.getMappedClass(type);
        for (final Entry<String, Object> entry : sort.entrySet()) {
            Object value = entry.getValue();
            boolean metaScore = value instanceof Document && ((Document) value).get("$meta") != null;
            mapped.put(new PathTarget(mapper, mappedClass, entry.getKey(), !metaScore).translatedPath(), value);
        }
        iterable.sort(mapped);
    }
    return iterable;
}
 
Example 4
Source File: QueryConverter.java    From sql-to-mongo-db-query-converter with Apache License 2.0 4 votes vote down vote up
/**
 * @param mongoDatabase the database to run the query against.
 * @param <T> variable based on the type of query run.
 * @return When query does a find will return QueryResultIterator&lt;{@link org.bson.Document}&gt;
 *           When query does a count will return a Long
 *           When query does a distinct will return QueryResultIterator&lt;{@link java.lang.String}&gt;
 * @throws ParseException when the sql query cannot be parsed
 */
@SuppressWarnings("unchecked")
public <T> T run(MongoDatabase mongoDatabase) throws ParseException {
    MongoDBQueryHolder mongoDBQueryHolder = getMongoQuery();

    MongoCollection mongoCollection = mongoDatabase.getCollection(mongoDBQueryHolder.getCollection());

    if (SQLCommandType.SELECT.equals(mongoDBQueryHolder.getSqlCommandType())) {
    	
        if (mongoDBQueryHolder.isDistinct()) {
            return (T) new QueryResultIterator<>(mongoCollection.distinct(getDistinctFieldName(mongoDBQueryHolder), mongoDBQueryHolder.getQuery(), String.class));
        } else if (sqlCommandInfoHolder.isCountAll() && !isAggregate(mongoDBQueryHolder)) {
            return (T) Long.valueOf(mongoCollection.count(mongoDBQueryHolder.getQuery()));
        } else if (isAggregate(mongoDBQueryHolder)) {
            
            AggregateIterable aggregate = mongoCollection.aggregate(generateAggSteps(mongoDBQueryHolder,sqlCommandInfoHolder));

            if (aggregationAllowDiskUse != null) {
                aggregate.allowDiskUse(aggregationAllowDiskUse);
            }

            if (aggregationBatchSize != null) {
                aggregate.batchSize(aggregationBatchSize);
            }

            return (T) new QueryResultIterator<>(aggregate);
        } else {
            FindIterable findIterable = mongoCollection.find(mongoDBQueryHolder.getQuery()).projection(mongoDBQueryHolder.getProjection());
            if (mongoDBQueryHolder.getSort() != null && mongoDBQueryHolder.getSort().size() > 0) {
                findIterable.sort(mongoDBQueryHolder.getSort());
            }
            if (mongoDBQueryHolder.getOffset() != -1) {
                findIterable.skip((int) mongoDBQueryHolder.getOffset());
            }
            if (mongoDBQueryHolder.getLimit() != -1) {
                findIterable.limit((int) mongoDBQueryHolder.getLimit());
            }

            return (T) new QueryResultIterator<>(findIterable);
        }
    } else if (SQLCommandType.DELETE.equals(mongoDBQueryHolder.getSqlCommandType())) {
        DeleteResult deleteResult = mongoCollection.deleteMany(mongoDBQueryHolder.getQuery());
        return (T)((Long)deleteResult.getDeletedCount());
    } else {
        throw new UnsupportedOperationException("SQL command type not supported");
    }
}
 
Example 5
Source File: MongoCollectionFind.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase	db	= getMongoDatabase( _session, argStruct );
	
	String collection	= getNamedStringParam(argStruct, "collection", null);
	if ( collection == null )
		throwException(_session, "please specify a collection");
	
	cfData	query	= getNamedParam(argStruct, "query", null );
	if ( query == null )
		throwException(_session, "please specify query");
	
	int	size			= getNamedIntParam(argStruct, "size", -1 );
	int	skip			= getNamedIntParam(argStruct, "skip", -1 );
	cfData sort		= getNamedParam(argStruct, 		"sort", null );
	cfData fields	= getNamedParam(argStruct, 		"fields", null );
	
	try{
		MongoCollection<Document> col = db.getCollection(collection);

		// Get the initial cursor
		FindIterable<Document>	cursor;
		long start = System.currentTimeMillis();
		Document qry = getDocument(query);
		
		cursor = col.find( qry );
		
		if ( fields != null )
			cursor = cursor.projection( getDocument(fields) );

		// Are we sorting?
		if ( sort != null )
			cursor	= cursor.sort( getDocument(sort) );
		
		// Are we limiting
		if ( skip != -1 )
			cursor	= cursor.skip(skip);
		
		// How many we bringing back
		if ( size != -1 )
			cursor = cursor.limit(size);

		// Now we can run the query
		cfArrayData	results	= cfArrayData.createArray(1);
		
		cursor.forEach( new Block<Document>() {

			@SuppressWarnings( "rawtypes" )
			@Override
			public void apply( final Document st ) {
				try {
					results.addElement( tagUtils.convertToCfData( (Map)st ) );
				} catch ( cfmRunTimeException e ) {}
			}
		} );
		
		_session.getDebugRecorder().execMongo(col, "find", qry, System.currentTimeMillis()-start);
		
		return results;
	} catch (MongoException me){
		throwException(_session, me.getMessage());
		return null;
	}
}
 
Example 6
Source File: MDbOperation.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
   * Applies data set query properties and hints on DBCursor, except
   * for cursor limit.
   * @see #applyPropertiesToCursor(DBCursor,QueryProperties,boolean,boolean)
   */
  static void applyPropertiesToCursor( MongoIterable<Document> mongoIterable, QueryProperties queryProps, 
          boolean includeSortExpr )
  {
BasicDBObject sortExprObj = null;
      if( includeSortExpr )   // normally done only when executing a query to get full result set
      {
          
          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}", queryProps.getSortExpr() ),  //$NON-NLS-1$
                      ex );
          }
         
      }

// Map it to correct iterable object
FindIterable<Document> findIterable = null;
AggregateIterable<Document> aggregateIterable = null;
MapReduceIterable<Document> mapReduceIterable = null;
if ( mongoIterable instanceof FindIterable )
{
	findIterable = (FindIterable<Document>) mongoIterable;
}
else if ( mongoIterable instanceof AggregateIterable )
{
	aggregateIterable = (AggregateIterable<Document>) mongoIterable;
}
else if ( mongoIterable instanceof MapReduceIterable )
{
	mapReduceIterable = (MapReduceIterable<Document>) mongoIterable;
}
if ( findIterable == null
		&& aggregateIterable == null && mapReduceIterable == null )
{
	// Unknown type, return
}

if ( findIterable != null )
{
	if ( sortExprObj != null )
		findIterable.sort( sortExprObj );

	if ( queryProps.getBatchSize( ) > 0 )
		findIterable.batchSize( queryProps.getBatchSize( ) );

	if ( queryProps.getNumDocsToSkip( ) > 0 )
		findIterable.skip( queryProps.getNumDocsToSkip( ) );

	if ( queryProps.isPartialResultsOk( ) )
		findIterable.partial( true );
	// TODO: Remove hint from the UI
	// TODO: add Time out in the UI
	/*
	 * // hint is deprecated in 3.2 DBObject hintObj =
	 * queryProps.getIndexHintsAsParsedObject(); String hintValue =
	 * queryProps.getIndexHints(); 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 ); }
	 * findIterable.maxTime(Bytes.QUERYOPTION_NOTIMEOUT, arg1) if(
	 * queryProps.hasNoTimeOut() ) rowsCursor.addOption(
	 * Bytes.QUERYOPTION_NOTIMEOUT );
	 */
}
if ( aggregateIterable != null )
{
	if ( queryProps.getBatchSize( ) > 0 )
		aggregateIterable.batchSize( queryProps.getBatchSize( ) );

}
if ( mapReduceIterable != null )
{
	if ( sortExprObj != null )
		mapReduceIterable.sort( sortExprObj );

	if ( queryProps.getBatchSize( ) > 0 )
		mapReduceIterable.batchSize( queryProps.getBatchSize( ) );
}
  }