Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

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

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:com.softlyinspired.jlw.reports.ReportReference.java

License:Open Source License

/**
 * //w  w  w  .  jav a2 s .co m
 * @return boolean - true if report id exists
 */
public boolean checkExisting() {
    /**
     * Returns if report reference exists or not;
     */
    boolean IdExists;
    try {
        /* Get the database collection */
        DBCollection coll = repoConnection.getReportsCollection();
        if (coll == null) {
            return false;
        }
        ;

        BasicDBObject query = new BasicDBObject();
        query.put("reportId", reportId);

        DBCursor checkDoc = coll.find(query).limit(1);
        if (checkDoc.count() == 0) {
            IdExists = false;
        } else {
            IdExists = true;
            currentReportDoc = checkDoc.next();
            reportName = currentReportDoc.get("name").toString();
            reportType = currentReportDoc.get("type").toString();
            reportDescription = currentReportDoc.get("description").toString();
            reportCategory = currentReportDoc.get("category").toString();
            reportLocation = currentReportDoc.get("reportLocation").toString();
        }

    } catch (Exception e) {
        System.out.println("Report does not exist");
        IdExists = false;
    }
    return IdExists;
}

From source file:com.spring.tutorial.dropbox.DropBoxAuth.java

public void removeJunk(String id, DbxClient client, String path) throws UnknownHostException, Exception {

    List<String> paths = new ArrayList<>();
    getDropboxPaths(id, paths, "/");

    MongoData mongoData = new MongoData();
    DB db = mongoData.getDB();/* ww w .j  ava2 s.co m*/
    DBCollection collection = db.getCollection(id + "_dropbox_files_meta");
    DBCursor cursor = collection.find();

    if (cursor.count() != 0) {
        while (cursor.hasNext()) {
            boolean found = false;
            DBObject doc = cursor.next();
            for (String onePath : paths) {
                if (doc.get("path").equals(onePath)) {
                    found = true;
                }
            }
            if (found == false) {
                collection.remove(doc);
            }
        }
    }
}

From source file:com.staticvillage.recommender.indexer.MongoDBIndexer.java

License:Apache License

@Override
public List<Place> getBeans() throws IndexerException {
    DBCollection dbCollection = instanceDB.getCollection(collection);
    DBCursor cursor = dbCollection.find();

    ArrayList<Place> places = new ArrayList<Place>(cursor.count());
    try {//from  w  w w  .  j  av  a  2  s .  c  om
        while (cursor.hasNext()) {
            places.add(fromDBObject(cursor.next()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return places;
}

From source file:com.staticvillage.recommender.indexer.MongoDBIndexer.java

License:Apache License

@Override
public List<Place> getBeans(Object obj) throws IndexerException {
    GeoPoint geoPoint = (GeoPoint) obj;/*www . ja v  a 2s  .  c  o m*/

    BasicDBObject near = new BasicDBObject();
    near.put("geometry", toGeoJSON(geoPoint.getLatitude(), geoPoint.getLongitude()));
    near.put("$maxDistance", 1609);

    BasicDBObject query = new BasicDBObject();
    query.put("$near", near);

    DBCollection dbCollection = instanceDB.getCollection(collection);
    DBCursor cursor = dbCollection.find(query);

    ArrayList<Place> places = new ArrayList<Place>(cursor.count());
    try {
        while (cursor.hasNext()) {
            places.add(fromDBObject(cursor.next()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return places;
}

From source file:com.stratio.deep.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Calculates shard chunks./*from ww  w. ja v a  2 s  .c  om*/
 *
 * @param collection the collection
 * @return the deep partition [ ]
 */
private DeepPartition[] calculateShardChunks(DBCollection collection) {

    DBCursor chuncks = getChunks(collection);

    Map<String, String[]> shards = getShards(collection);

    MongoPartition[] deepPartitions = new MongoPartition[chuncks.count()];
    int i = 0;
    boolean keyAssigned = false;
    String key = null;
    while (chuncks.hasNext()) {

        DBObject dbObject = chuncks.next();
        if (!keyAssigned) {
            Set<String> keySet = ((DBObject) dbObject.get("min")).keySet();
            for (String s : keySet) {
                key = s;
                keyAssigned = true;
            }
        }
        deepPartitions[i] = new MongoPartition(
                mongoDeepJobConfig.getRddId(), i, new DeepTokenRange(shards.get(dbObject.get("shard")),
                        ((DBObject) dbObject.get("min")).get(key), ((DBObject) dbObject.get("max")).get(key)),
                key);
        i++;
    }
    List<MongoPartition> mongoPartitions = Arrays.asList(deepPartitions);

    Collections.shuffle(mongoPartitions);
    return mongoPartitions.toArray(new MongoPartition[mongoPartitions.size()]);
}

From source file:com.university.mongodb.courses.m101j.blogapplication.BlogPostDAO.java

License:Apache License

public List<DBObject> findByDateDescending(int limit) {

    List<DBObject> posts = null;
    // XXX HW 3.2, Work Here
    // Return a list of DBObjects, each one a post from the posts collection
    DBCursor cursor = postsCollection.find(new BasicDBObject()).limit(limit)
            .sort(new BasicDBObject(POST_DATE, -1));
    posts = new ArrayList<>(cursor.count());

    try {//from w  w w .  j a va2  s.  co  m
        posts = cursor.toArray();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return posts;
}

From source file:com.zuehlke.sbdfx.dataaccess.mongo.MongoCitiesDao.java

@Override
public ListResult<City> findByArea(final FindByAreaRequest req) {

    final MongoQueryBuilder b = new MongoQueryBuilder();

    b.numberBetween(req.getLatitudeMin(), "latitude", req.getLatitudeMax());
    b.numberBetween(req.getLongitudeMin(), "longitude", req.getLongitudeMax());

    final DBCursor cursor = cities.find(b.create()).limit(req.getMaxResults());
    final ListResult<City> result = ListResult.create(cursor.count());
    for (final DBObject dbObject : cursor) {
        result.add(toCity(dbObject));//  ww w  .j a v a  2  s. c o  m
    }
    return result;
}

From source file:controllers.Elements.java

License:Apache License

public static Result show(String id) {
    Logger.info("Select element with id: " + id);
    final List<String> names = Application.getCollectionNames();
    final PersistenceLayer pl = Configurator.getDefaultConfigurator().getPersistence();
    DBCursor cursor = pl.find(Constants.TBL_ELEMENTS, new BasicDBObject("_id", new ObjectId(id)));

    if (cursor.count() == 0) {
        Logger.info("Cursor selected " + cursor.count());
        return notFound("No such element exists in the db.");
    } else if (cursor.count() > 1) {
        Logger.info("Cursor selected " + cursor.count());
        return notFound("One or more objects with this id exist");
    } else {//from  w  w w  .j a  v a2s  .  c o m

        Element elmnt = DataHelper.parseElement(cursor.next(), pl);

        return ok(element.render(names, elmnt));
    }

}

From source file:controllers.Elements.java

License:Apache License

public static Result listElements(String collection, int batch, int offset) {
    final List<String> names = Application.getCollectionNames();

    if (collection == null) {
        return ok(elements.render(names, null));
    }/*from   w w w. j  a  va2 s  . c o m*/

    final List<Element> result = new ArrayList<Element>();
    final PersistenceLayer pl = Configurator.getDefaultConfigurator().getPersistence();

    BasicDBObject query = new BasicDBObject();
    query.put("collection", collection);
    Filter filter = Application.getFilterFromSession();
    if (filter != null) {
        query = Application.getFilterQuery(filter);
        System.out.println("Objects Query: " + query);
    }

    final DBCursor cursor = pl.getDB().getCollection(Constants.TBL_ELEMENTS).find(query).skip(offset)
            .limit(batch);

    Logger.info("Cursor has: " + cursor.count() + " objects");

    while (cursor.hasNext()) {
        final Element e = DataHelper.parseElement(cursor.next(), pl);

        if (e.getName() == null) {
            e.setName("missing name");
        }

        result.add(e);
    }

    return ok(elements.render(names, result));
}

From source file:controllers.FilterController.java

License:Apache License

public static Result remove(String property) {
    Logger.debug("in method remove(String property), removing filter with property " + property);
    PersistenceLayer p = Configurator.getDefaultConfigurator().getPersistence();
    Filter filter = Application.getFilterFromSession();
    BasicDBObject query = new BasicDBObject("descriminator", filter.getDescriminator());
    query.put("collection", filter.getCollection());
    query.put("property", property);

    DBCursor cursor = p.find(Constants.TBL_FILTERS, query);
    if (cursor.count() == 0) {
        Logger.debug("No filter found for property: " + property);
    } else if (cursor.count() == 1) {
        Logger.debug("Removing filter for property: " + property);
        Filter tmp = DataHelper.parseFilter(cursor.next());
        p.getDB().getCollection(Constants.TBL_FILTERS).remove(tmp.getDocument());
    } else {/* www . j a v a2s. co m*/
        Logger.error("Something went wrong, while removing filter for property: " + property);
        throw new RuntimeException("Two many filters found for property " + property);
    }

    return ok();
}