Example usage for com.mongodb DBCursor size

List of usage examples for com.mongodb DBCursor size

Introduction

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

Prototype

public int size() 

Source Link

Document

Counts the number of objects matching the query this does take limit/skip into consideration

Usage

From source file:org.alfresco.bm.file.FileDataServiceImpl.java

License:Open Source License

@Override
public FileData getRandomFile(String fileset, String extension) {
    long count = fileCount(fileset, extension);
    if (count == 0L) {
        // There is nothing to choose from
        return null;
    }/* ww  w .j  a  v  a  2s  .  co m*/
    // Use a random number from 0 (inclusive) to 'count' (exclusive)
    int skip = (int) (Math.random() * (double) count);

    DBObject queryObj = BasicDBObjectBuilder.start().add(FIELD_FILESET, fileset).add(FIELD_EXTENSION, extension)
            .get();
    DBCursor results = collection.find(queryObj).skip(skip).limit(1);
    if (results.size() == 0) {
        // No results
        return null;
    } else {
        DBObject fileDataObj = results.next();
        return fromDBObject(fileDataObj);
    }
}

From source file:org.alfresco.repo.domain.node.mongo.MongoNodeDAO.java

License:Open Source License

@Override
public NodeEntity getByVersionLabel(long nodeId, String versionLabel) {
    NodeEntity nodeEntity = null;/*w w w. jav a2s. co  m*/

    DBObject query = QueryBuilder.start("n").is(nodeId).and("vl").is(versionLabel).and("c").is(true).get();
    DBObject orderBy = BasicDBObjectBuilder.start("v", -1).get();
    DBCursor cursor = nodes.find(query).sort(orderBy).limit(1);
    try {
        int size = cursor.size();
        if (size > 1) {
            throw new RuntimeException();
        } else if (size == 1) {
            DBObject dbObject = cursor.next();
            nodeEntity = toNodeEntity(dbObject);
        }
    } finally {
        cursor.close();
    }

    return nodeEntity;
}

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;//from w  ww.ja v 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.apache.camel.processor.idempotent.mongodb.MongoDbIdempotentRepository.java

License:Apache License

/**
 * Returns true if this repository contains the specified element.
 *///ww w.ja va 2  s . c  o  m
public boolean contains(String key) {

    if (!this.isId()) {
        key = DigestUtils.md5Hex(key);
    }

    log.debug("contains --> " + key);

    // object to search
    DBObject criteria = new BasicDBObject(EVENTID, key);

    // find object
    DBCursor cursor = coll.find(criteria);

    if (cursor.size() == 0) {
        return false;
    } else {
        return true;
    }
}

From source file:org.apache.chemistry.opencmis.mongodb.MongodbUtils.java

License:Apache License

public BasicDBObject getNodeByPath(String path, DBCollection collection) {

    String[] pathSplit = path.split(PATH_SEPARATOR);
    int pathDepth = pathSplit.length - 1;

    DBCursor candidates = collection
            .find(new BasicDBObject().append("title", pathSplit[pathDepth]).append("level", "pathDepth"));

    // if number of candidates is one, then we have found our content item - return it
    if (candidates.size() == 1) {
        return (BasicDBObject) candidates.next();
    }/*  w w w. j a  v  a  2 s. co m*/
    // if number of candidates is greater than the path depth, then just follow the depth instead

    if (candidates.size() >= pathSplit.length) {
        int currentLevel = 1;
        DBObject currentNode = collection.findOne(new BasicDBObject().append("title", "root"));

        while (currentLevel <= pathDepth && currentNode != null) {
            currentNode = collection.findOne(
                    new BasicDBObject().append("left", new BasicDBObject("$gt", currentNode.get("left")))
                            .append("right", new BasicDBObject("$gt", currentNode.get("right")))
                            .append("title", pathSplit[currentLevel]).append("level", currentLevel));
            currentLevel++;
        }
        return (BasicDBObject) currentNode;
    } else {
        int pathLevel = pathDepth - 1;
        DBObject candidate = null;

        while (candidates.hasNext() && pathLevel > 0) {
            candidate = candidates.next();
            DBCursor ancestors = collection
                    .find(new BasicDBObject("left", new BasicDBObject().append("$lt", candidate.get("left")))
                            .append("right", new BasicDBObject().append("$gt", candidate.get("right"))))
                    .sort(new BasicDBObject("left", 1));

            DBObject ancestor = ancestors.next();
            while (ancestor != null && ancestor.get("title").equals(pathSplit[pathLevel]) && pathLevel > -1) {
                ancestor = ancestors.next();
                pathLevel--;
            }
        }
        return (BasicDBObject) candidate;
    }
}

From source file:org.apache.gora.mongodb.query.MongoDBResult.java

License:Apache License

/**
 * Save the reference to the cursor that holds the actual results.
 *
 * @param cursor/*ww w . jav a2s  . c o  m*/
 *          {@link DBCursor} obtained from a query execution and that holds
 *          the actual results
 */
public void setCursor(DBCursor cursor) {
    this.cursor = cursor;
    this.size = cursor.size();
}

From source file:org.benjp.services.mongodb.NotificationServiceImpl.java

License:Open Source License

public int getUnreadNotificationsTotal(String user, String type, String category, String categoryId) {
    int total = -1;
    DBCollection coll = db().getCollection(M_NOTIFICATIONS);
    BasicDBObject query = new BasicDBObject();

    query.put("user", user);
    //    query.put("isRead", false);
    if (type != null)
        query.put("type", type);
    if (category != null)
        query.put("category", category);
    if (categoryId != null)
        query.put("categoryId", categoryId);
    DBCursor cursor = coll.find(query);
    total = cursor.size();

    return total;
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}//from   w ww  . j  ava  2s  .  co  m
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> T create(T t) {
    if (t == null) {
        return null;
    }

    BasicDBObject object = new BasicDBObject();

    Class<?> type = t.getClass();
    DBCollection coll = db.getCollection(type.getSimpleName());

    Long key = t.getOid();
    if (key == null) {
        // Set a new object identifier.
        DBCursor cursor = coll.find();
        key = (long) cursor.size() + 1;
        cursor.close();
    }
    t.setOid(key);

    if (find(t.getClass(), key) != null) {
        return null;
    }

    List<Field> fields = getDeclaredFields(type, new LinkedList<Field>());
    List<Method> methods = getDeclaredMethods(type, new LinkedList<Method>());

    for (Field field : fields) {
        for (Method method : methods) {
            // Call a getter method.
            if (("get" + field.getName()).equalsIgnoreCase(method.getName())) {
                try {
                    object.put(field.getName(), method.invoke(t));
                } catch (IllegalAccessException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                } catch (InvocationTargetException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                }
                break;
            }
        }
    }

    try {
        LOG.log(Level.INFO, "{0}", t);
        WriteResult writeResult = coll.insert(object);
        if (writeResult.getError() != null) {
            LOG.log(Level.WARNING, "Insertion of {0} is failed.", t);
        }
    } catch (MongoException e) {
        LOG.log(Level.SEVERE, "Insertion of " + t + " is failed.", e);
    }

    return t;
}

From source file:org.eobjects.analyzer.storage.MongoDbRowAnnotationFactory.java

License:Open Source License

@Override
public InputRow[] getRows(RowAnnotation annotation) {
    final String annotationColumnName = getColumnName(annotation);

    final BasicDBObject query = new BasicDBObject();
    query.put(annotationColumnName, true);

    logger.info("Finding all rows with annotation column: {}", annotationColumnName);
    final DBCursor cursor = _dbCollection.find(query);
    InputRow[] rows = new InputRow[cursor.size()];

    int i = 0;/*  w w w . j  av a2s.  c om*/
    while (cursor.hasNext()) {
        DBObject dbRow = cursor.next();
        Object rowId = dbRow.get(ROW_ID_KEY);
        Object distinctCount = dbRow.get(DISTINCT_COUNT_KEY);
        MockInputRow row;

        if (rowId != null) {
            row = new MockInputRow(((Number) rowId).intValue());
        } else {
            row = new MockInputRow();
        }
        row.put(distinctCountColumn, distinctCount);

        Set<Entry<InputColumn<?>, String>> columnEntries = _inputColumnNames.entrySet();
        for (Entry<InputColumn<?>, String> entry : columnEntries) {
            InputColumn<?> column = entry.getKey();
            String columnName = entry.getValue();
            Object value = dbRow.get(columnName);
            if (value != null) {
                row.put(column, value);
            }
        }

        rows[i] = row;
        i++;
    }

    logger.info("Returning {} distinct rows", rows.length);

    return rows;
}

From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java

License:Apache License

@SuppressWarnings("hiding")
@Override/*from  www  .  j  av a 2s  .  c o 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;
        }
    });
}