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:controllers.FilterController.java

License:Apache License

private static Graph getOrdinalGraph(Filter filter, String property) {
    Graph g = null;//from  w ww  . java  2s.  c o  m
    if (filter != null) {
        BasicDBObject ref = new BasicDBObject("descriminator", filter.getDescriminator());
        DBCursor cursor = Configurator.getDefaultConfigurator().getPersistence().find(Constants.TBL_FILTERS,
                ref);
        if (cursor.count() == 1) { // only root filter
            g = FilterController.getGraph(filter.getCollection(), property);
        } else {
            g = FilterController.getGraph(filter, property);
        }

    }

    return g;
}

From source file:controllers.Overview.java

License:Apache License

public static Result index() {
    final List<String> names = Application.getCollectionNames();
    Filter filter = Application.getFilterFromSession();

    Statistics stats = null;/* w  ww . ja v  a  2s. c  o  m*/
    GraphData data = null;
    if (filter != null) {
        BasicDBObject ref = new BasicDBObject("descriminator", filter.getDescriminator());
        ref.put("collection", session(WebAppConstants.CURRENT_COLLECTION_SESSION));
        DBCursor cursor = Configurator.getDefaultConfigurator().getPersistence().find(Constants.TBL_FILTERS,
                ref);

        Logger.info("filter is not null");
        if (cursor.count() == 1) { // only root filter
            Logger.info("filter has no parent, using cached statistics");
            // used cached results
            stats = FilterController.getCollectionStatistics(filter.getCollection());
            data = Overview.getDefaultGraphs(filter, true);
        } else {
            // calculate new results
            stats = FilterController.getCollectionStatistics(filter);

            List<String> properties = new ArrayList<String>();
            while (cursor.hasNext()) {
                Filter tmp = DataHelper.parseFilter(cursor.next());
                if (tmp.getProperty() != null) {
                    properties.add(tmp.getProperty());
                }
            }
            data = Overview.getAllGraphs(filter, properties);
        }

    }
    return ok(overview.render(names, data, stats));
}

From source file:DataAccess.DAO.ItemDAO.java

public String updateItem(Item item) {
    try {/*ww w.j  a v a2s. c o m*/
        if (connectDB()) {
            BasicDBObject whereQuery = new BasicDBObject();
            whereQuery.put("id_item", item.getId());
            DBCursor cursor = coll.find(whereQuery);
            if (cursor.count() < 1) {
                return "Item not found";
            }
            while (cursor.hasNext()) {
                DBObject updateDocument = cursor.next();
                updateDocument.put("name", item.getName());
                updateDocument.put("description", item.getDescription());
                updateDocument.put("price", item.getPrice().longValue());
                updateDocument.put("stock", item.getStock());
                updateDocument.put("shop_id", item.getShopid());
                coll.update(whereQuery, updateDocument);
            }
            System.out.println("Document updated (Item) successfully");
            return "Success, Item " + item.getId() + " updated ";
        } else {
            return "Fail";
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        return "Fail";
    }
}

From source file:DataAccess.DAO.ItemDAO.java

public String deleteItem(int itemId) {
    try {/*  w  w w .jav a2s  .  c o m*/
        if (connectDB()) {
            BasicDBObject whereQuery = new BasicDBObject();
            whereQuery.put("id_item", itemId);
            DBCursor cursor = coll.find(whereQuery);
            if (cursor.count() < 1) {
                return "Item " + itemId + " was not found";
            }
            coll.remove(whereQuery);
            System.out.println("Document deleted successfully");
            return "Success, Item " + itemId + " deleted";
        } else {
            return "Fail";
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        return "Fail";
    }
}

From source file:DataBase.JavaMongoDB.java

public ArrayList<DBObject> Consultar(BasicDBObject Consulta, boolean lista) {
    long time_start, time_end;
    time_start = System.currentTimeMillis();
    DBCursor cur = col.find(Consulta);
    time_end = System.currentTimeMillis();
    time = (time_end - time_start);/*  w w w  .  ja  v a 2 s. c  o m*/

    if (lista) {
        ArrayList<DBObject> Lista = new ArrayList<>();
        // DBObject a;
        for (int i = 0; i < cur.count(); i++) {
            System.out.println("Mongo conulat" + time);
            DBObject a = cur.next();
            Lista.add(a);
        }
        cur.close();
        return Lista;
    } else {
        return null;
    }

}

From source file:db.AbstractTable.java

public DBObject getById(int ID) {
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("id", ID);
    DBCursor cursor = linkToTable.find(searchQuery);
    if (cursor.count() == 0) {
        return null;
    }//from w w  w .  ja  v  a 2 s .c o  m
    return cursor.next();
}

From source file:dbscan.DBScanMapper.java

License:Apache License

/**
 * The map function read the points in input. All points are not read and not clusterized
 * for the input query execute in MongoDb from Hadoop.
 * If a point has enought points in neighborhood, then a cluster will be emitted and the
 * point is marked as clusterized; otherwise, do nothing.
 *
 * @param pointKey the key of the point in input
 * @param pointValue the point in input, in BSON (binary JSon)
 * @param pointContext the context in which map-reduce works
 *//* w  w w. j av  a  2  s  .c o  m*/
@Override
public void map(final ObjectId pointKey, final BSONObject pointValue, final Context pointContext)
        throws IOException, InterruptedException {

    // the point is not visited and not clustered
    // see mongo.input.query in mongo-dbscan.xml

    // mark point as visited
    pointValue.put("visited", new Boolean(true));

    // query for *near points
    // *near: points within the radius with same hashtag
    Object locationAndRadius[] = { pointValue.get("loc"), new Double(radius / 111.12) };
    BasicDBObject centerQuery = new BasicDBObject("$center", locationAndRadius);
    BasicDBObject withinQuery = new BasicDBObject("$within", centerQuery);

    BasicDBObject findNearPoints = new BasicDBObject();
    findNearPoints.put("loc", withinQuery);
    findNearPoints.put("hashtag", pointValue.get("hashtag"));

    DBCursor nearPoints = collection.find(findNearPoints);

    // if near points are enough -> create cluster
    if (nearPoints.count() >= minPointsToCreateCluster) {

        // mark point as clusterized
        pointValue.put("clusterized", new Boolean(true));

        // new cluster
        BSONWritable newCluster = new BSONWritable();

        // create key
        BSONObject loc = (BSONObject) pointValue.get("loc");
        int lat, lon;
        if (loc.get("lat") instanceof Double)
            lat = ((Double) loc.get("lat")).intValue();
        else
            lat = (Integer) loc.get("lat");
        if (loc.get("lon") instanceof Double)
            lon = ((Double) loc.get("lon")).intValue();
        else
            lon = (Integer) loc.get("lon");
        // Final key
        String newClusterKey = pointValue.get("hashtag") + "_" + lat + "," + lon;

        // add points (the first of the cluster)
        newCluster.put("numPoints", 1);

        // add location
        DecimalFormat df = new DecimalFormat("###.####");
        String formattedLat, formattedLon;
        if (loc.get("lat") instanceof Double)
            formattedLat = df.format(((Double) loc.get("lat")));
        else
            formattedLat = df.format(((Integer) loc.get("lat")));
        if (loc.get("lon") instanceof Double)
            formattedLon = df.format(((Double) loc.get("lon")));
        else
            formattedLon = df.format(((Integer) loc.get("lon")));
        Map<String, Float> clusterLoc = new TreeMap<String, Float>();
        clusterLoc.put("lat", Float.parseFloat(formattedLat));
        clusterLoc.put("lon", Float.parseFloat(formattedLon));
        newCluster.put("loc", clusterLoc);

        // add near points (analyzed by reduce)
        Map<ObjectId, BSONObject> mapNearPoints = new HashMap<ObjectId, BSONObject>();
        while (nearPoints.hasNext()) {
            BSONObject o = nearPoints.next();
            mapNearPoints.put((ObjectId) o.get("_id"), o);
        }
        newCluster.put("neighborPoints", mapNearPoints);

        // add date
        newCluster.put("createdAt", new Date());

        // add hashtag
        newCluster.put("hashtag", pointValue.get("hashtag"));

        // emit new cluster
        //System.out.println("Emit new candidate cluster with " + mapNearPoints.size() + " points in neighborhood");
        pointContext.write(new Text(newClusterKey), newCluster);

    }

    // update point in Mongo
    // the point is now visited and *maybe clusterized
    // *maybe because could not be enought points in neighborhood
    BasicDBObject findOldPoint = new BasicDBObject("_id", pointValue.get("_id"));
    BasicDBObject newPoint = new BasicDBObject(pointValue.toMap());
    collection.findAndModify(findOldPoint, newPoint);

}

From source file:de.fhg.igd.mongomvcc.impl.internal.Tree.java

License:Open Source License

@Override
public long[] getChildren(long cid) {
    if (cid != 0 && !existsCommit(cid)) {
        throw new VException("Unknown commit: " + cid);
    }/*w ww  .j av a2 s . co  m*/
    DBCursor c = _commits.find(new BasicDBObject(PARENT_CID, cid), new BasicDBObject(MongoDBConstants.ID, 1));
    long[] r = new long[c.count()];
    int i = 0;
    for (DBObject o : c) {
        r[i++] = (Long) o.get(MongoDBConstants.ID);
    }
    return r;
}

From source file:de.fhg.igd.mongomvcc.impl.MongoDBVMaintenance.java

License:Open Source License

private long[] doFindUnreferencedDocuments(String collection, long expiry, TimeUnit unit) {
    long maxTime = getMaxTime(expiry, unit);

    //fetch the OIDs of all documents older than the expiry time
    DBCollection collDocs = _db.getDB().getCollection(collection);
    DBCursor docs = collDocs.find(
            new BasicDBObject(MongoDBConstants.TIMESTAMP,
                    new BasicDBObject("$not", new BasicDBObject("$gte", maxTime))), //also include docs without a timestamp
            new BasicDBObject(MongoDBConstants.ID, 1));
    IdSet oids = new IdHashSet(docs.count());
    for (DBObject o : docs) {
        oids.add((Long) o.get(MongoDBConstants.ID));
    }/* w w w.j  av a 2  s .  com*/

    //iterate through all commits and eliminate referenced documents
    DBCollection collCommits = _db.getDB().getCollection(MongoDBConstants.COLLECTION_COMMITS);
    for (DBObject o : collCommits.find()) {
        Commit c = Tree.deserializeCommit(o);
        Map<String, IdMap> allObjs = c.getObjects();
        IdMap objs = allObjs.get(collection);
        if (objs != null) {
            //eliminate OIDs referenced by this commit
            IdMapIterator mi = objs.iterator();
            while (mi.hasNext()) {
                mi.advance();
                oids.remove(mi.value());
            }
        }
    }

    //the remaining OIDs must be the unreferenced ones
    return oids.toArray();
}

From source file:de.uni_koeln.spinfo.maalr.mongo.core.Database.java

License:Apache License

public LexEntryList queryForLexEntries(String login, Role role, Verification verification, String verifier,
        long startTime, long endTime, Status[] states, int limit, int offset, String orderField,
        boolean ascending) {
    logger.info("Query Params: " + login + ", " + role + ", " + verification + ", " + startTime + ", " + endTime
            + ", " + states + ", " + limit + ", " + offset + ", " + orderField + ", " + ascending);
    DBCursor cursor = query(login, role, verification, verifier, startTime, endTime, states, limit, offset,
            orderField, ascending);/*from  w w w .j a  va2s  . c  om*/
    List<LexEntry> results = new ArrayList<LexEntry>();
    while (cursor.hasNext()) {
        DBObject next = cursor.next();
        LexEntry entry = Converter.convertToLexEntry(next);
        results.add(entry);
    }
    int count = cursor.count();
    cursor.close();
    return new LexEntryList(results, count);
}