Example usage for com.mongodb DBCollection count

List of usage examples for com.mongodb DBCollection count

Introduction

In this page you can find the example usage for com.mongodb DBCollection count.

Prototype

public long count(@Nullable final DBObject query) 

Source Link

Document

Same as #getCount(DBObject)

Usage

From source file:com.tomtom.speedtools.mongodb.DaoUtils.java

License:Apache License

/**
 * Returns number of entities that satisfy a specified query filter. When the collections is large and indexes are
 * missing this call can be a performance killer.
 *
 * @param collection Collection to get the entity from.
 * @param query      The query to select the entity.
 * @return The number of objects in the collection for the given query.
 * @throws InternalDaoException Thrown when an unknown error has occurred. The error will have been logged.
 *///from  w w w .  j  a va 2  s.c o  m
public static long count(@Nonnull final DBCollection collection, @Nonnull final MongoDBQuery query)
        throws InternalDaoException {
    assert collection != null;
    assert query != null;

    try {
        LOG.debug("count: collection={}, query={}", collection.getName(), query);
        return collection.count(query.toDBObject());
    } catch (final MapperException e) {
        final String message = "Entity could not be mapped: " + query + ", collection=" + collection.getName()
                + '.';
        LOG.error("count: " + message, e);
        throw new InternalDaoException(message, e);
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

@Override
public CentralPurgeQueryResults getPagedSortedFilteredPurgeStates(EzSecurityToken token,
        List<CentralPurgeStatus> statuses, int pageNum, int numPerPage)
        throws EzSecurityTokenException, CentralPurgeServiceException {

    DBCollection purgeColl = null;
    Mongo mongoClient = null;//  w  ww  .jav a  2  s .co  m
    AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token)
            .arg("event", "getPagedSortedFilteredPurgeStates").arg("statuses", statuses).arg("pageNum", pageNum)
            .arg("numPerPage", numPerPage);
    try {
        validateCentralPurgeSecurityToken(token);

        // Get access to the purge collection within Mongo
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);

        List<CentralPurgeState> result = new ArrayList<>();
        List<Integer> statusesValues = new LinkedList<>();
        for (CentralPurgeStatus status : statuses) {
            statusesValues.add(status.getValue());
        }

        // Gets all centralPurgeStates that are in the statuses and pages
        BasicDBObject query = new BasicDBObject(
                EzCentralPurgeServiceHelpers.CentralPurgeStateString + "."
                        + EzCentralPurgeServiceHelpers.CentralPurgeStatusString,
                new BasicDBObject("$in", statusesValues));
        DBCursor cursor = purgeColl.find(query).sort(new BasicDBObject(PurgeId, -1))
                .skip(pageNum > 0 ? ((pageNum - 1) * numPerPage) : 0).limit(numPerPage);

        // Decodes each centralPurgeState from how it's stored in MongoDB and adds it to the return variable
        for (DBObject dbObject : cursor) {
            CentralPurgeState centralPurgeState = decodeCentralPurgeState(
                    (DBObject) dbObject.get(CentralPurgeStateString));
            result.add(centralPurgeState);
        }
        CentralPurgeQueryResults centralPurgeQueryResults = new CentralPurgeQueryResults();
        centralPurgeQueryResults.setPurgeStates(result);
        centralPurgeQueryResults.setCount(purgeColl.count(query));
        return centralPurgeQueryResults;
    } catch (EzSecurityTokenException e) {
        logError(e, evt, "CentralPurgeService failed when trying to validate token:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw e;
    } catch (UnknownHostException e) {
        logError(e, evt, "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredPurgeStates:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredPurgeStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
    } catch (Exception e) {
        logError(e, evt, "CentralPurgeService encountered an exception in getPagedSortedFilteredPurgeStates:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService encountered an exception in getPagedSortedFilteredPurgeStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
    } finally {
        auditLogger.logEvent(evt);
        logEventToPlainLogs(logger, evt);
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

@Override
public CentralAgeOffEventQueryResults getPagedSortedFilteredAgeOffEventStates(EzSecurityToken token,
        List<CentralPurgeStatus> statuses, int pageNum, int numPerPage)
        throws EzSecurityTokenException, CentralPurgeServiceException {
    DBCollection ageOffColl = null;
    Mongo mongoClient = null;/*from ww  w  .  j av a  2s  .  c o  m*/
    AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token)
            .arg("event", "getPagedSortedFilteredAgeOffEventStates").arg("statuses", statuses)
            .arg("pageNum", pageNum).arg("numPerPage", numPerPage);
    try {
        validateCentralPurgeSecurityToken(token);

        // Get access to the ageoff collection within Mongo

        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        ageOffColl = mongoDB.getCollection(AGEOFF_COLLECTION);

        List<CentralAgeOffEventState> result = new ArrayList<>();
        List<Integer> statusesValues = new LinkedList<>();
        for (CentralPurgeStatus status : statuses) {
            statusesValues.add(status.getValue());
        }

        // Gets all centralPurgeStates that are in the statuses and pages
        BasicDBObject query = new BasicDBObject(
                EzCentralPurgeServiceHelpers.CentralAgeOffStateString + "."
                        + EzCentralPurgeServiceHelpers.CentralPurgeStatusString,
                new BasicDBObject("$in", statusesValues));
        DBCursor cursor = ageOffColl.find(query).sort(new BasicDBObject(AgeOffEventId, -1))
                .skip(pageNum > 0 ? ((pageNum - 1) * numPerPage) : 0).limit(numPerPage);

        for (DBObject dbObject : cursor) {
            CentralAgeOffEventState centralAgeOffEventState = decodeCentralAgeOffEventState(
                    (DBObject) dbObject.get(CentralAgeOffStateString));
            result.add(centralAgeOffEventState);
        }
        CentralAgeOffEventQueryResults centralAgeOffEventQueryResults = new CentralAgeOffEventQueryResults();
        centralAgeOffEventQueryResults.setAgeOffEventStates(result);
        centralAgeOffEventQueryResults.setCount(ageOffColl.count(query));
        return centralAgeOffEventQueryResults;
    } catch (EzSecurityTokenException e) {
        logError(e, evt, "CentralPurgeService failed when trying to validate token:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw e;
    } catch (UnknownHostException e) {
        logError(e, evt,
                "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredAgeOffEventStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredAgeOffEventStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
    } catch (Exception e) {
        logError(e, evt,
                "CentralPurgeService encountered an exception in getPagedSortedFilteredAgeOffEventStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService encountered an exception in getPagedSortedFilteredAgeOffEventStates:["
                        + e.getClass().getName() + ":" + e.getMessage() + "]");
    } finally {
        auditLogger.logEvent(evt);
        logEventToPlainLogs(logger, evt);
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSource.java

License:Open Source License

/**
 * Gets the number of records for a given query
 * /*from   www .  java 2 s  .c o m*/
 * @param json
 *          the json query
 * @param collectionName
 *          the collection name to query
 * @return the number of records for the query, -1 if there is an error
 */
public int countQuery(String json, String collectionName) {

    DBObject dbObject = (DBObject) JSON.parse(json);
    DB database = getDatabase();
    DBCollection collection = database.getCollection(collectionName);
    return (int) collection.count(dbObject);

}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void countChunks(Message<Buffer> message, JsonObject json) {
    String filesId = json.getString("files_id");
    if (filesId == null || filesId.trim().isEmpty()) {
        replyError(message, "Invalid file id.");
        return;//from   w w  w . j a v a2 s .  com
    }
    try {
        DBObject file = BasicDBObjectBuilder.start("files_id", filesId).get();
        DBCollection collection = db.getCollection(bucket + CHUNKS);
        long count = collection.count(file);
        message.reply(count);
    } catch (RuntimeException e) {
        logger.error(e.getMessage(), e);
        replyError(message, e.getMessage());
    }
}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbDataContext.java

License:Apache License

@Override
protected Number executeCountQuery(Table table, List<FilterItem> whereItems,
        boolean functionApproximationAllowed) {
    final DBCollection collection = _mongoDb.getCollection(table.getName());

    final DBObject query = createMongoDbQuery(table, whereItems);

    logger.info("Executing MongoDB 'count' query: {}", query);
    final long count = collection.count(query);

    return count;
}

From source file:org.einherjer.week2.samples.FindCriteriaSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection collection = db.getCollection("findCriteriaSample");
    collection.drop();//from www  .j a  v  a 2 s  .  c o m

    // insert 10 documents with two random integers
    for (int i = 0; i < 10; i++) {
        collection
                .insert(new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100)));
    }

    //1- The query document can be created by using a QueryBuilder...
    QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70);
    //2- or, the query document can be created manually
    DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", 10).append("$lt", 90));

    System.out.println("\nCount:");
    long count = collection.count(builder.get());
    System.out.println(count);

    System.out.println("\nFind all: ");
    DBCursor cursor = collection.find(builder.get());
    try {
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur);
        }
    } finally {
        cursor.close();
    }
}

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);
        if (p.getOffset() > 0) {
            cursor.skip(p.getOffset());//from   w w  w  . jav a 2  s. co m
        }
        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.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

/**
 * Gets the count of documents in collection that would match a criteria.
 *
 * @param clazz the collection class.// w ww  .  jav  a 2  s. c  om
 * @param query specifies the selection criteria.
 * @return the number of documents that matches selection criteria.
 */
public long count(Class<?> clazz, Query query) {
    DBCollection collection = getCollection(clazz);
    return collection.count(query != null ? query.toDbObject() : null);
}

From source file:org.fastmongo.odm.repository.MongoTemplate.java

License:Apache License

@Override
public long count(Class<?> collectionClass, Query query) {
    DBCollection collection = getCollection(collectionClass);
    return collection.count(query.toDbObject());
}