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:com.linuxbox.enkive.workspace.searchResult.mongo.MongoSearchResultUtils.java

License:Open Source License

protected List<String> sortMessages(Collection<String> messageIds, String sortField, int sortDirection,
        int pageNum, int pageSize) throws ResultPageException {
    ArrayList<String> sortedIds = new ArrayList<String>();
    // Only want to return the ids
    BasicDBObject keys = new BasicDBObject();
    keys.put("_id", 1);
    keys.put(sortField, 1);/* w  ww . j  av  a 2s  .  c  om*/

    BasicDBObject query = new BasicDBObject();
    // Build object with IDs
    BasicDBList idList = new BasicDBList();
    idList.addAll(messageIds);
    BasicDBObject idQuery = new BasicDBObject();
    idQuery.put("$in", idList);
    query.put("_id", idQuery);
    // Add sort query

    DBCursor results = messageColl.find(query, keys);
    BasicDBObject orderBy = new BasicDBObject();
    orderBy.put(sortField, sortDirection);
    try {
        results = results.sort(orderBy).skip((pageNum - 1) * pageSize).limit(pageSize);
        for (DBObject result : results)
            sortedIds.add((String) result.get("_id"));
    } catch (MongoException e) {
        // Mongo failed to get the page.  Create an error message for the user.
        throw new ResultPageException("MongoDB failed to get the requested page of results", e);
    }
    return sortedIds;
}

From source file:com.linuxbox.enkive.workspace.searchResult.mongo.MongoSearchResultUtils.java

License:Open Source License

public List<String> sortSearchResults(Collection<String> searchResultIds, String sortField, int sortDirection,
        int pageNum, int pageSize) {
    ArrayList<String> sortedIds = new ArrayList<String>(pageSize);
    // Only want to return the ids
    BasicDBObject keys = new BasicDBObject();
    keys.put("_id", 1);
    keys.put(sortField, 1);//from w  w  w . j ava 2s . c o  m

    BasicDBObject query = new BasicDBObject();
    // Build object with IDs
    BasicDBList idList = new BasicDBList();
    for (String Id : searchResultIds)
        idList.add(ObjectId.massageToObjectId(Id));

    BasicDBObject idQuery = new BasicDBObject();
    idQuery.put("$in", idList);
    query.put("_id", idQuery);
    // Add sort query

    DBCursor results = searchResultColl.find(query, keys);
    BasicDBObject orderBy = new BasicDBObject();
    orderBy.put(sortField, sortDirection);
    results = results.sort(orderBy).skip((pageNum - 1) * pageSize).limit(pageSize);
    for (DBObject result : results.toArray())
        sortedIds.add((String) result.get("_id"));

    return sortedIds;
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

@Override
public List<DBObject> findAll(String entityName, String projection, Pageable page) {
    if (page == null) {
        page = new PageRequest(0, Integer.MAX_VALUE);
    }/*w w  w  .  j a  v  a  2  s.  c o  m*/

    DBCursor cursor = null;
    if (StringUtils.isEmpty(projection)) {
        cursor = getCollection(entityName).find(new BasicDBObject());
    } else {
        String[] properties = projection.split(",");
        BasicDBObjectBuilder projectionBuilder = BasicDBObjectBuilder.start();
        boolean idWanted = false;
        for (String property : properties) {
            property = property.trim();
            if (!StringUtils.isEmpty(property)) {
                if (property.equals(EntityUtils.ID)) {
                    idWanted = true;
                }

                projectionBuilder.add(property.trim(), true);
            }
        }

        if (idWanted == false) {
            projectionBuilder.append("_id", false);
        }

        cursor = getCollection(entityName).find(new BasicDBObject(), projectionBuilder.get())
                .sort(new BasicDBObject(projection, 1));
    }

    if (page.getSort() != null) {
        cursor = cursor.sort(createSort(page));
    } else if (projection != null) {
        cursor = cursor.sort(new BasicDBObject(projection, 1));
    }

    cursor = cursor.skip(page.getOffset()).limit(page.getPageSize());

    List<DBObject> result = cursor.toArray();
    return result;
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}//from ww  w  .  ja  v a  2  s.  c o  m
 * 
 */
@Override
public List<DBObject> findAllByQuery(DBObject query, String projection, Pageable page) {
    DBCursor cursor = null;
    if (StringUtils.isEmpty(projection)) {
        cursor = getCollection().find(query);
    } else {
        cursor = getCollection().find(query, new BasicDBObject(projection, true).append("_id", false));
    }

    if (page.getSort() != null) {
        cursor = cursor.sort(createSort(page));
    } else if (projection != null) {
        cursor = cursor.sort(new BasicDBObject(projection, 1));
    }

    cursor = cursor.skip(page.getOffset()).limit(page.getPageSize());

    List<DBObject> result = cursor.toArray();
    return result;
}

From source file:com.mysema.query.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, QueryModifiers modifiers,
        List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where));
    if (modifiers.getLimit() != null) {
        cursor.limit(modifiers.getLimit().intValue());
    }//from  ww  w .j  a v  a2s .c o m
    if (modifiers.getOffset() != null) {
        cursor.skip(modifiers.getOffset().intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    return cursor;
}

From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java

License:Open Source License

private void doAcquireNextTriggers(Map<TriggerKey, OperableTrigger> triggers, Date noLaterThanDate,
        int maxCount) throws JobPersistenceException {
    BasicDBObject query = new BasicDBObject();
    query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", noLaterThanDate));

    DBCursor cursor = triggerCollection.find(query);

    BasicDBObject sort = new BasicDBObject();
    sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1));
    cursor.sort(sort);

    log.debug("Found {} triggers which are eligible to be run.", cursor.count());

    while (cursor.hasNext() && maxCount > triggers.size()) {
        DBObject dbObj = cursor.next();/*  w  w w  .j a  va 2 s .c o  m*/

        OperableTrigger trigger = toTrigger(dbObj);

        try {

            if (trigger == null) {
                continue;
            }

            if (triggers.containsKey(trigger.getKey())) {
                log.debug("Skipping trigger {} as we have already acquired it.", trigger.getKey());
                continue;
            }

            if (trigger.getNextFireTime() == null) {
                log.debug("Skipping trigger {} as it has no next fire time.", trigger.getKey());

                // No next fire time, so delete it
                removeTrigger(trigger.getKey());
                continue;
            }

            // deal with misfires
            if (applyMisfire(trigger)) {
                log.debug("Misfire trigger {}.", trigger.getKey());

                Date nextFireTime = trigger.getNextFireTime();

                if (nextFireTime == null) {
                    log.debug("Removing trigger {} as it has no next fire time after the misfire was applied.",
                            trigger.getKey());

                    // No next fire time, so delete it
                    removeTrigger(trigger.getKey());
                    continue;
                }

                // The trigger has misfired and was rescheduled, its firetime may be too far in the future
                // and we don't want to hang the quartz scheduler thread up on <code>sigLock.wait(timeUntilTrigger);</code> 
                // so, check again that the trigger is due to fire
                if (nextFireTime.after(noLaterThanDate)) {
                    log.debug("Skipping trigger {} as it misfired and was scheduled for {}.", trigger.getKey(),
                            trigger.getNextFireTime());
                    continue;
                }
            }

            log.debug("Inserting lock for trigger {}", trigger.getKey());

            BasicDBObject lock = new BasicDBObject();
            lock.put(KEY_NAME, dbObj.get(KEY_NAME));
            lock.put(KEY_GROUP, dbObj.get(KEY_GROUP));
            lock.put(LOCK_INSTANCE_ID, instanceId);
            lock.put(LOCK_TIME, new Date());
            // A lock needs to be written with FSYNCED to be 100% effective across multiple servers
            locksCollection.insert(lock, WriteConcern.FSYNCED);

            log.debug("Aquired trigger {}", trigger.getKey());
            triggers.put(trigger.getKey(), trigger);

        } catch (DuplicateKey e) {

            // someone else acquired this lock. Move on.
            log.debug("Failed to acquire trigger {} due to a lock", trigger.getKey());

            BasicDBObject lock = new BasicDBObject();
            lock.put(KEY_NAME, dbObj.get(KEY_NAME));
            lock.put(KEY_GROUP, dbObj.get(KEY_GROUP));

            DBObject existingLock;
            DBCursor lockCursor = locksCollection.find(lock);
            if (lockCursor.hasNext()) {
                existingLock = lockCursor.next();
                // support for trigger lock expirations
                if (isTriggerLockExpired(existingLock)) {
                    log.warn("Lock for trigger {} is expired - removing lock and retrying trigger acquisition",
                            trigger.getKey());
                    removeTriggerLock(trigger);
                    doAcquireNextTriggers(triggers, noLaterThanDate, maxCount - triggers.size());
                }
            } else {
                log.warn("Error retrieving expired lock from the database. Maybe it was deleted");
                doAcquireNextTriggers(triggers, noLaterThanDate, maxCount - triggers.size());
            }
        }
    }
}

From source file:com.querydsl.mongodb.AbstractMongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit);// w  w w  .  j  a va2 s . co  m
    }
    if (offset != null) {
        cursor.skip(offset);
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}

From source file:com.querydsl.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, Expression<?> projection,
        QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where), createProjection(projection));
    Integer limit = modifiers.getLimitAsInteger();
    Integer offset = modifiers.getOffsetAsInteger();
    if (limit != null) {
        cursor.limit(limit.intValue());/*w  ww . j av a 2s . co  m*/
    }
    if (offset != null) {
        cursor.skip(offset.intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    if (readPreference != null) {
        cursor.setReadPreference(readPreference);
    }
    return cursor;
}

From source file:com.redhat.lightblue.crud.mongo.BasicDocFinder.java

License:Open Source License

@Override
public long find(CRUDOperationContext ctx, DBCollection coll, DBObject mongoQuery, DBObject mongoSort,
        Long from, Long to) {
    LOGGER.debug("Submitting query");
    DBCursor cursor = new FindCommand(null, coll, mongoQuery, null).execute();
    LOGGER.debug("Query evaluated");
    if (mongoSort != null) {
        cursor = cursor.sort(mongoSort);
        LOGGER.debug("Result set sorted");
    }/*from  www.  j  ava2  s  .c o  m*/
    long ret = cursor.size();
    LOGGER.debug("Applying limits: {} - {}", from, to);
    if (from != null) {
        cursor.skip(from.intValue());
    }
    if (to != null) {
        cursor.limit(to.intValue() - (from == null ? 0 : from.intValue()) + 1);
    }
    LOGGER.debug("Retrieving results");
    List<DBObject> mongoResults = cursor.toArray();
    LOGGER.debug("Retrieved {} results", mongoResults.size());
    List<JsonDoc> jsonDocs = translator.toJson(mongoResults);
    ctx.addDocuments(jsonDocs);
    for (DocCtx doc : ctx.getDocuments()) {
        doc.setOperationPerformed(Operation.FIND);
    }
    LOGGER.debug("Translated DBObjects to json");
    return ret;
}

From source file:com.redhat.lightblue.mongo.crud.BasicDocFinder.java

License:Open Source License

@Override
public long find(CRUDOperationContext ctx, DBCollection coll, DBObject mongoQuery, DBObject mongoProjection,
        DBObject mongoSort, Long from, Long to) {
    LOGGER.debug("Submitting query {}", mongoQuery);

    long executionTime = System.currentTimeMillis();
    DBCursor cursor = null;
    boolean cursorInUse = false;
    try {//from  ww  w .j  a  v  a2  s .co m
        cursor = coll.find(mongoQuery, mongoProjection);
        if (readPreference != null) {
            cursor.setReadPreference(readPreference);
        }

        if (ctx.isLimitQueryTime() && maxQueryTimeMS > 0) {
            cursor.maxTime(maxQueryTimeMS, TimeUnit.MILLISECONDS);
        }

        executionTime = System.currentTimeMillis() - executionTime;

        LOGGER.debug("Query evaluated");
        if (mongoSort != null) {
            cursor = cursor.sort(mongoSort);
            LOGGER.debug("Result set sorted");
        }

        LOGGER.debug("Applying limits: {} - {}", from, to);
        boolean retrieve = true;
        int nRetrieve = 0;
        int numMatched = 0;
        // f and t are from and to indexes, both inclusive
        int f = from == null ? 0 : from.intValue();
        if (f < 0) {
            f = 0;
        }
        cursor.skip(f);
        if (ctx.isComputeCounts()) {
            numMatched = cursor.count();
        }
        int t;
        if (to != null) {
            t = to.intValue();
            if (t < f) {
                retrieve = false;
            } else {
                cursor.limit(nRetrieve = t - f + 1);
            }
        } else {
            if (ctx.isComputeCounts()) {
                t = numMatched - 1;
                nRetrieve = numMatched - f;
            } else {
                t = Integer.MAX_VALUE;
            }
        }
        if (retrieve) {
            LOGGER.debug("Retrieving results");
            CursorStream stream = new CursorStream(cursor, translator, mongoQuery, executionTime, f, t);
            ctx.setDocumentStream(stream);
            cursorInUse = true;
        } else {
            ctx.setDocumentStream(new ListDocumentStream<DocCtx>(new ArrayList<>()));
        }
        if (RESULTSET_LOGGER.isDebugEnabled() && (executionTime > 100)) {
            RESULTSET_LOGGER.debug("execution_time={}, query={}, from={}, to={}", executionTime, mongoQuery, f,
                    t);
        }
        return numMatched;
    } finally {
        if (cursor != null && !cursorInUse) {
            cursor.close();
        }
    }
}