Example usage for com.mongodb DBCursor sort

List of usage examples for com.mongodb DBCursor sort

Introduction

In this page you can find the example usage for com.mongodb DBCursor sort.

Prototype

public DBCursor sort(final DBObject orderBy) 

Source Link

Document

Sorts this cursor's elements.

Usage

From source file:net.ymate.platform.persistence.mongodb.impl.MongoGridFSSession.java

License:Apache License

public List<GridFSDBFile> findAll(OrderBy orderBy, Page page) {
    DBCursor _cursor = __dbCollection.find();
    if (orderBy != null) {
        _cursor.sort(orderBy.toBson());
    }//from w w  w .jav  a  2 s.c om
    if (page != null && page.page() > 0 && page.pageSize() > 0) {
        _cursor.skip((page.page() - 1) * page.pageSize()).limit(page.pageSize());
    }
    List<GridFSDBFile> _results = new ArrayList<GridFSDBFile>();
    while (_cursor.hasNext()) {
        _results.add((GridFSDBFile) _cursor.next());
    }
    _cursor.close();
    return _results;
}

From source file:net.ymate.platform.persistence.mongodb.impl.MongoGridFSSession.java

License:Apache License

public List<GridFSDBFile> find(Query query, OrderBy orderBy, Page page) {
    DBCursor _cursor = __dbCollection.find(query.toBson());
    if (orderBy != null) {
        _cursor.sort(orderBy.toBson());
    }//from  w w w . j a v a2  s  . co  m
    if (page != null && page.page() > 0 && page.pageSize() > 0) {
        _cursor.skip((page.page() - 1) * page.pageSize()).limit(page.pageSize());
    }
    List<GridFSDBFile> _results = new ArrayList<GridFSDBFile>();
    while (_cursor.hasNext()) {
        _results.add((GridFSDBFile) _cursor.next());
    }
    _cursor.close();
    return _results;
}

From source file:net.ymate.platform.persistence.mongodb.support.DefaultMongoQuery.java

License:Apache License

public IMongoQuery<T> executeQuery(int pageNumber, int pageSize) throws OperatorException {
    if (!__isExecuted) {
        List<T> _results = new ArrayList<T>();
        Long _recordCount = 0L;//from  w w w.ja va2 s .  c om
        if (__orderBy != null || pageNumber != 0 || pageSize != 0) {
            DBCursor _cursor = __collection.find(this.__condition, __customFields);
            if (__orderBy != null) {
                _cursor.sort(__orderBy);
            }
            if (pageNumber > 0 && pageSize > 0) {
                _cursor.skip((pageNumber - 1) * pageSize).limit(pageSize);
                _recordCount = executeCount();
            }
            while (_cursor.hasNext()) {
                DBObject _obj = _cursor.next();
                _results.add(__handler.handle(_obj));
            }
        } else {
            DBObject _obj = __collection.findOne(this.__condition, __customFields);
            if (_obj != null) {
                _results.add(__handler.handle(_obj));
            }
        }
        __isExecuted = true;
        this.__resultSet = new PageResultSet<T>(_results, pageNumber, pageSize, _recordCount.intValue());
    }
    return this;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventRecord> getResults(String eventName, int skip, int limit) {
    DBObject queryObj = QueryBuilder.start().get();
    if (eventName != null) {
        queryObj.put(EventRecord.FIELD_EVENT_NAME, eventName);
    }/*from  w w w. j av a 2  s .  co  m*/
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventRecord> results = new ArrayList<EventRecord>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventRecord eventRecord = convertToEventRecord(obj);
            results.add(eventRecord);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "\n" + "Found results: \n" + "   Query:          " + queryObj + "\n" + "   Skip:           "
                        + skip + "\n" + "   Limit:          " + limit + "\n" + "   Results:        " + size);
    }
    return results;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventRecord> getResults(long startTime, long endTime, boolean chartOnly, int skip, int limit) {
    QueryBuilder queryBuilder = QueryBuilder.start().and(EventRecord.FIELD_START_TIME)
            .greaterThanEquals(new Date(startTime)).and(EventRecord.FIELD_START_TIME)
            .lessThan(new Date(endTime));
    if (chartOnly) {
        queryBuilder.and(EventRecord.FIELD_CHART).is(true);
    }//from  w w w.j  a  v a 2 s  .  c  o m
    DBObject queryObj = queryBuilder.get();
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventRecord> results = new ArrayList<EventRecord>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventRecord eventRecord = convertToEventRecord(obj);
            results.add(eventRecord);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "\n" + "Found results: \n" + "   Query:          " + queryObj + "\n" + "   Skip:           "
                        + skip + "\n" + "   Limit:          " + limit + "\n" + "   Results:        " + size);
    }
    return results;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventDetails> getEventDetails(EventResultFilter filter, String filterEventName, int skip,
        int limit) {
    QueryBuilder queryBuilder = QueryBuilder.start();

    // apply filter
    switch (filter) {
    case Failed://from   www.  ja v  a 2s . c o  m
        queryBuilder.and(EventRecord.FIELD_SUCCESS).is(false);
        break;

    case Success:
        queryBuilder.and(EventRecord.FIELD_SUCCESS).is(true);
        break;
    default:
        break;
    }

    //apply event name filter
    if (null != filterEventName && !filterEventName.isEmpty()) {
        queryBuilder.and(EventRecord.FIELD_EVENT_NAME).is(filterEventName);
    }

    DBObject queryObj = queryBuilder.get();
    // sort descending to get the newest values first
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(-1))
            .get();
    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventDetails> results = new ArrayList<EventDetails>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventDetails eventDetails = convertToEventDetails(obj);
            results.add(eventDetails);
        }
    } finally {
        cursor.close();
    }

    return results;
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

protected void doFindAll(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in the collection
    DBObject query = null;/* ww w . j av  a  2  s. c  o m*/
    // do not run around looking for a type converter unless there is a need for it
    if (exchange.getIn().getBody() != null) {
        query = exchange.getIn().getBody(DBObject.class);
    }
    DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class);

    // get the batch size and number to skip
    Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class);
    Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class);
    Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class);
    DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class);
    DBCursor ret = null;
    try {
        if (query == null && fieldFilter == null) {
            ret = dbCol.find(new BasicDBObject());
        } else if (fieldFilter == null) {
            ret = dbCol.find(query);
        } else {
            ret = dbCol.find(query, fieldFilter);
        }

        if (sortBy != null) {
            ret.sort(sortBy);
        }

        if (batchSize != null) {
            ret.batchSize(batchSize.intValue());
        }

        if (numToSkip != null) {
            ret.skip(numToSkip.intValue());
        }

        if (limit != null) {
            ret.limit(limit.intValue());
        }

        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll);
        resultMessage.setBody(ret.toArray());
        resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count());
        resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size());

    } catch (Exception e) {
        // rethrow the exception
        throw e;
    } finally {
        // make sure the cursor is closed
        if (ret != null) {
            ret.close();
        }
    }

}

From source file:org.axonframework.eventsourcing.eventstore.mongo.AbstractEventStorageStrategy.java

License:Apache License

@Override
public List<? extends TrackedEventData<?>> findTrackedEvents(DBCollection eventCollection,
        TrackingToken lastToken, int batchSize) {
    DBCursor cursor;
    if (lastToken == null) {
        cursor = eventCollection.find(BasicDBObjectBuilder.start().get());
    } else {// w  w w . j  a v  a2 s .  c o  m
        Assert.isTrue(lastToken instanceof LegacyTrackingToken,
                String.format("Token %s is of the wrong type", lastToken));
        LegacyTrackingToken legacyTrackingToken = (LegacyTrackingToken) lastToken;
        cursor = eventCollection.find(BasicDBObjectBuilder.start()
                .add(eventConfiguration.timestampProperty(),
                        new BasicDBObject("$gte", legacyTrackingToken.getTimestamp().toString()))
                .add(eventConfiguration.sequenceNumberProperty(),
                        new BasicDBObject("$gte", legacyTrackingToken.getSequenceNumber()))
                .get());
    }
    cursor = cursor.sort(new BasicDBObject(eventConfiguration().timestampProperty(), ORDER_ASC)
            .append(eventConfiguration().sequenceNumberProperty(), ORDER_ASC));
    cursor = applyBatchSize(cursor, batchSize);
    try {
        return stream(cursor.spliterator(), false).flatMap(this::extractTrackedEvents)
                .filter(event -> event.trackingToken().isAfter(lastToken)).limit(batchSize)
                .collect(Collectors.toList());
    } finally {
        cursor.close();
    }
}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * MongoDB find with all parameters./*from  ww w .  ja  va  2  s .  c  om*/
 * @param handler Database handler
 * @param col collection
 * @param query Query parameters
 * @param opt options in Map like: {"limit":2}
 * @param field  Projection
 * @return Item
 * @throws QueryException
 */
public Item find(final Str handler, final Item col, final Item query, final Item opt, final Item projection)
        throws QueryException {
    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        DBObject p = null;
        if (opt != null && opt instanceof Str) {
            p = getDbObjectFromStr(opt);
        } else if (projection != null && projection instanceof Str) {
            p = getDbObjectFromStr(projection);
        }
        final DBObject q = query != null ? getDbObjectFromStr(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBCursor cursor = coll.find(q, p);
        Map options = null;
        options = (opt != null && opt instanceof Map) ? (Map) opt
                : (projection != null && projection instanceof Map) ? (Map) projection : null;
        if (options != null) {
            Value keys = options.keys();
            for (final Item key : keys) {
                if (!(key instanceof Str))
                    throw MongoDBErrors.generalExceptionError("String expected " + key.toJava());
                final String k = ((Str) key).toJava();
                final Value v = options.get(key, null);
                if (v instanceof Str || v.type().instanceOf(SeqType.ITR)) {
                    if (k.equals(LIMIT)) {
                        if (v.type().instanceOf(SeqType.ITR_OM)) {
                            long l = ((Item) v).itr(null);
                            cursor.limit((int) l);
                        } else {
                            throw MongoDBErrors
                                    .generalExceptionError("Number Expected for key '" + key.toJava() + "'");
                        }
                    } else if (k.equals(SKIP)) {
                        //cursor.skip(Token.toInt(v));
                    } else if (k.equals(SORT)) {
                        BasicDBObject sort = new BasicDBObject(k, v);
                        sort.append("name", "-1");
                        cursor.sort((DBObject) sort);
                    } else if (k.equals(COUNT)) {
                        int count = cursor.count();
                        BasicDBObject res = new BasicDBObject();
                        res.append("count", count);
                        return objectToItem(handler, res);
                    } else if (k.equals(EXPLAIN)) {
                        DBObject result = cursor.explain();
                        return objectToItem(handler, result);
                    }
                } else if (v instanceof Map) {
                } else {
                    throw MongoDBErrors.generalExceptionError("Invalid value 2...");
                }
            }
        }
        return cursorToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * MongoDB find with all parameters.//from w w  w  . ja  v  a  2  s  . c  om
 * @param handler database handler Database handler
 * @param col collection collection
 * @param query Query parameters
 * @param opt options in Map like: {"limit":2}
 * @param projection projection (selection field)
 * @return Item
 * @throws QueryException query exception
 */
public Item find(final Str handler, final Item col, final Item query, final Item opt, final Item projection)
        throws QueryException {
    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        DBObject p = null;
        if (opt != null && opt instanceof Str) {
            p = getDbObjectFromItem(opt);
        } else if (projection != null && projection instanceof Str) {
            p = getDbObjectFromItem(projection);
        }
        final DBObject q = query != null ? getDbObjectFromItem(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBCursor cursor = coll.find(q, p);
        Map options = null;
        options = (opt != null && opt instanceof Map) ? (Map) opt
                : (projection != null && projection instanceof Map) ? (Map) projection : null;
        if (options != null) {
            Value keys = options.keys();
            for (final Item key : keys) {
                if (!(key instanceof Str))
                    throw MongoDBErrors.generalExceptionError("String expected " + key.toJava());
                final String k = ((Str) key).toJava();
                final Value v = options.get(key, null);
                if (v instanceof Str || v.seqType().instanceOf(SeqType.ITR)) {
                    if (k.equals(LIMIT)) {
                        if (v.seqType().instanceOf(SeqType.ITR_OM)) {
                            long l = ((Item) v).itr(null);
                            cursor.limit((int) l);
                        } else {
                            throw MongoDBErrors
                                    .generalExceptionError("Number Expected for key '" + key.toJava() + "'");
                        }
                    } else if (k.equals(SKIP)) {
                        //cursor.skip(Token.toInt(v));
                    } else if (k.equals(SORT)) {
                        BasicDBObject sort = new BasicDBObject(k, v);
                        sort.append("name", "-1");
                        cursor.sort(sort);
                    } else if (k.equals(COUNT)) {
                        int count = cursor.count();
                        BasicDBObject res = new BasicDBObject();
                        res.append("count", count);
                        return objectToItem(handler, res);
                    } else if (k.equals(EXPLAIN)) {
                        DBObject result = cursor.explain();
                        return objectToItem(handler, result);
                    }
                } else if (v instanceof Map) {
                } else {
                    throw MongoDBErrors.generalExceptionError("Invalid value 2...");
                }
            }
        }
        return cursorToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}