Example usage for com.mongodb DBCollection getCount

List of usage examples for com.mongodb DBCollection getCount

Introduction

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

Prototype

public long getCount() 

Source Link

Document

Get the count of documents in collection.

Usage

From source file:com.cubeia.poker.handhistory.storage.DatabaseStorageService.java

License:Open Source License

private void initHandsCollection() {
    mongoStorage.map(HistoricHand.class);
    //Indexing/*from  ww w . j  a  v a  2 s.  c om*/
    DBCollection coll = mongoStorage.getCollection(HistoricHand.class.getSimpleName());
    if (0 == coll.getCount()) {
        coll.createIndex(new BasicDBObject("startTime", -1));
    }
}

From source file:com.hangum.tadpole.mongodb.core.test.ConAndAuthentication.java

License:Open Source License

/**
 * collection info/*from   w ww  .  j av a 2s  .com*/
 * 
 * @param db
 * @param collection
 * @return
 */
public String getCollectionInfo(DB db, String collection) {
    DBCollection coll = db.getCollection(collection);

    System.out.println("#################################################");
    System.out.println("[collection name]" + coll.getName());
    System.out.println("[count]" + coll.getCount());

    // index list
    List<DBObject> listIndex = coll.getIndexInfo();
    List<CollectionFieldDAO> columnInfo = MongoDBTableColumn.tableColumnInfo(listIndex,
            db.getCollection(collection).findOne());
    for (CollectionFieldDAO collectionFieldDAO : columnInfo) {
        System.out.println("[field]" + collectionFieldDAO.getField());

        if (!collectionFieldDAO.getChildren().isEmpty()) {
            List<CollectionFieldDAO> childColl = collectionFieldDAO.getChildren();
            for (CollectionFieldDAO collectionFieldDAO2 : childColl) {
                System.out.println("\t [child field]" + collectionFieldDAO2.getField());

                if (!collectionFieldDAO2.getChildren().isEmpty()) {
                    List<CollectionFieldDAO> childColl2 = collectionFieldDAO2.getChildren();
                    for (CollectionFieldDAO collectionFieldDAO3 : childColl2) {
                        System.out.println("\t\t [child field]" + collectionFieldDAO3.getField());
                    }

                }
            }

        }
    }

    //      //
    //      StringBuffer sbJson = new StringBuffer();
    //
    //      DBCursor cursor = coll.find();
    //      while (cursor.hasNext()) {
    //         DBObject dbObj = cursor.next();
    //         String jsonData = dbObj.toString();
    //         System.out.println("[data] \t" + jsonData);
    //
    //         sbJson.append(jsonData);
    //      }
    //
    //      System.out
    //            .println("#####[fully text]#########################################################");

    // System.out.println("\t\t ******[detail data][start]*******************************************");
    // ObjectMapper om = new ObjectMapper();
    // try {
    // Map<String, Object> mapObj = om.readValue(sbJson.toString(),
    // new TypeReference<Map<String, Object>>() {});
    // System.out.println("[json to object]" + mapObj);
    //
    // Set<String> keys = mapObj.keySet();
    // for (String key : keys) System.out.print(key + "\t:\t");
    // System.out.println();
    //
    //
    // } catch (JsonParseException e) {
    // e.printStackTrace();
    // } catch (JsonMappingException e) {
    // e.printStackTrace();
    // } catch (IOException e) {
    // e.printStackTrace();
    // }

    System.out.println("\t\t ******[detail data][end]*******************************************");

    return "";
}

From source file:com.ibm.bluemix.smartveggie.dao.UserDaoImpl.java

@Override
public BasicDBObject updateUser(UserDTO userDTO) {
    BasicDBObject updates = null;//from   www  .  java  2  s.  c  om
    try {
        System.out.println("Updating Users...");
        DB db = MongodbConnection.getMongoDB();
        DBCollection col = db.getCollection(ICollectionName.COLLECTION_USERS);

        BasicDBObject query = new BasicDBObject();
        query.append("userName", userDTO.getUserName());
        System.out.println("Updating Record: " + query);

        updates = new BasicDBObject();
        if ((userDTO.getFirstName() != null) && (userDTO.getFirstName() != ""))
            updates.append("firstName", userDTO.getFirstName());
        if ((userDTO.getLastName() != null) && (userDTO.getLastName() != ""))
            updates.append("lastName", userDTO.getLastName());
        if ((userDTO.getAddressLine1() != null) && (userDTO.getAddressLine1() != ""))
            updates.append("addressLine1", userDTO.getAddressLine1());
        if ((userDTO.getAddressLine2() != null) && (userDTO.getAddressLine2() != ""))
            updates.append("addressLine2", userDTO.getAddressLine2());
        if ((userDTO.getAge() > 0) && (userDTO.getAge() < 100))
            updates.append("age", userDTO.getAge());
        if ((userDTO.getSex() != null) && (userDTO.getSex() != ""))
            updates.append("sex", userDTO.getSex());
        if ((userDTO.getUserName() != null) && (userDTO.getUserName() != ""))
            updates.append("userName", userDTO.getUserName());
        if ((userDTO.getPassword() != null) && (userDTO.getPassword() != ""))
            updates.append("password", userDTO.getPassword());
        if ((userDTO.getCity() != null) && (userDTO.getCity() != ""))
            updates.append("city", userDTO.getCity());
        if ((userDTO.getPinCode() != null) && (userDTO.getPinCode() != ""))
            updates.append("pin", userDTO.getPinCode());
        if ((userDTO.getUserTypeCode() != null) && (userDTO.getUserTypeCode() != "")) {
            updates.append("userType", userDTO.getUserTypeCode());
            if (userDTO.getUserTypeCode().equalsIgnoreCase("vendor")) {
                if ((userDTO.getLicenseNo() != null) && (userDTO.getLicenseNo() != "")) {
                    updates.append("licenseNo", userDTO.getLicenseNo());

                    //Process the date field
                    SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
                    String validFrom = userDTO.getValidFrom();
                    String validTo = userDTO.getValidTo();

                    try {

                        Date validFromDate = formatter.parse(validFrom);
                        Date validToDate = formatter.parse(validTo);
                        System.out.println(validFromDate);
                        updates.append("validFrom", validFromDate);
                        updates.append("validTo", validToDate);
                        //System.out.println(formatter.format(validFromDate));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (userDTO.getUserTypeCode().equalsIgnoreCase("regulator")) {
                if (userDTO.getRegulatingCityCode() != null && userDTO.getRegulatingCityCode() != null) {
                    updates.append("regulatingCityCode", userDTO.getRegulatingCityCode());
                }
                if (userDTO.getRegulatingCityCode() != null && userDTO.getRegulatingCityCode() != null) {
                    updates.append("regulatingCityName", userDTO.getRegulatingCityName());
                }
            }
        }
        System.out.println("Querying for update: " + query);
        col.update(query, updates);
        System.out.println("col after update" + col.toString() + col.getCount());

    } catch (Exception e) {
        throw e;
    }
    return updates;
}

From source file:com.jaspersoft.mongodb.importer.MongoDbImporter.java

License:Open Source License

public void validate(String tableName) {
    DBCollection collection = mongodbConnection.getMongoDatabase().getCollection(tableName);
    long size = collection.getCount();
    if (size == 0) {
        logger.error("No data in Mongo database");
        return;/* ww w. j av a  2  s . c om*/
    }
    logger.info("Elements in collection: " + size);
    logger.info("Validating the first 5 entries");
    DBCursor cursor = collection.find().limit(5);
    DBObject object;
    Object value;
    logger.info("---------------");
    while (cursor.hasNext()) {
        object = cursor.next();
        for (String id : object.keySet()) {
            value = object.get(id);
            logger.info(value + " -> " + value.getClass().getName());
        }
        logger.info("---------------");
    }
}

From source file:com.malsolo.mongodb.humongous.driver.Main.java

public static void main(String... args) throws UnknownHostException {

    MongoClient mongoClient = new MongoClient();
    DB db = mongoClient.getDB("news");

    Set<String> colls = db.getCollectionNames();

    for (String s : colls) {
        System.out.println(s);//from ww  w .j a  v  a2s.  c  om
    }

    DBCollection coll = db.getCollection("article");

    BasicDBObject doc = new BasicDBObject("authorId", UUID.randomUUID()).append("author", "Driver")
            .append("date", new Date()).append("title", "Title");
    coll.insert(doc);

    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    System.out.println(coll.getCount());

    try (DBCursor cursor = coll.find()) {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void insertWord(List<TweetDBEntity> list) {

    DBCollection collection = dbConnection();
    if (collection != null) {
        BasicDBObject document;/*from  w  w  w  .j av  a2 s.co m*/

        for (TweetDBEntity twit : list) {
            document = new BasicDBObject();
            document.append("text", twit.getText());
            document.append("rootType", twit.getRootType());
            document.append("polarity", twit.getPolarity());
            collection.insert(document);
            System.out.println(collection.getCount() + " ---" + twit.getText() + " tweet'i yazld");
        }
    }
}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void insertExpression(List<Expressions> list) {

    DBCollection collection = dbConnectionForExpression();
    if (collection != null) {
        BasicDBObject document;//from w w w  .j  a va2 s.  c o  m

        for (Expressions exp : list) {
            document = new BasicDBObject();
            document.append("text", exp.getExpression());
            document.append("polarity", Polarity.getPolarityValue(exp.getPolarity()));
            collection.insert(document);
            System.out.println(
                    collection.getCount() + "---------    " + Polarity.getPolarityValue(exp.getPolarity())
                            + " ---" + exp.getExpression() + " Deyim'i yazld");
        }
    }
}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Get count of documents in DB//from ww  w. ja v a 2 s .  c om
 * 
 * @param collection
 *            DBCollection object
 * @return count of documents
 */
public long getDocumentCount(DBCollection collection) {

    return collection.getCount();
}

From source file:com.original.service.channel.config.Initializer.java

License:Open Source License

/**
 * /*from w w  w  . j  av a  2  s .c  o m*/
 * @param db
 * @param collectionName
 * @param fileName
 * @param force
 * @throws IOException
 */
private void initCollection(DB db, String collectionName, String fileName, boolean force) throws IOException {
    DBCollection collection = db.getCollection(collectionName);
    if (collection.getCount() > 0 && !force) {
        logger.info(collectionName + " had existed!");
        return;
    }

    if (force && collection.getCount() > 0) {
        collection.drop();
        logger.info("force to init, drop the collection:" + collectionName);
    }
    BufferedReader br = null;
    if (fileName.startsWith("/")) {
        InputStream is = Initializer.class.getResourceAsStream(fileName);
        br = new BufferedReader(new InputStreamReader(is));
    } else {
        br = new BufferedReader(new FileReader(fileName));
    }

    StringBuffer fileText = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        fileText.append(line);
    }
    logger.info(collectionName + " Read:" + fileText);
    // System.out.println(profile);
    br.close();
    if (fileText != null) {
        // convert JSON to DBObject directly
        List<String> list = parseJsonItemsFile(fileText);
        for (String txt : list) {
            logger.info(collectionName + " init item:" + txt);
            DBObject dbObject = (DBObject) JSON.parse(txt);
            collection.insert(dbObject);
        }
    }
    logger.info(collectionName + " init Done:" + collection.count());
}

From source file:com.uquetignywebapp.common.MainServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www .  j a va2  s.c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, UnknownHostException, SQLException {
    System.out.println("Processrequest");
    String type = request.getParameter("choice");

    if (type == null || type.isEmpty()) {
    }
    String url = null;

    ArrayList<String> col = new ArrayList<>();
    ArrayList<String> colDbGeneral = new ArrayList<>();
    colDbGeneral = getCollections(colDbGeneral);
    if (type.equals("displayDB")) {
        url = "/dbViewer.jsp";
        col = getCollections(col);
        System.out.println("Taille Apres le getCollections " + col.size());
        request.setAttribute("collec", col);
    } else {
        url = "/personneViewer.jsp";
        DBCollection test = getSpecificCollection(type);
        System.out.println("Test.getCount");
        System.out.println(test.getCount());
        ArrayList<Map> test2 = fillSpecificCollection(test);
        request.setAttribute("prof", test2);
        System.out.println("Liste of champs ");
        ArrayList ar = getListofChamps(type, 1);
        System.out.println(ar.toString());
    }
    /* else if (type.equals("Professeur")) {
    url = "/personneViewer.jsp";
    DBCollection test = getSpecificCollection("Professeur");
    System.out.println("Test.getCount");
    System.out.println(test.getCount());
    ArrayList<Map> test2 = fillSpecificCollection(test);
    request.setAttribute("prof", test2);
    } else if (type.equals("Personne")) {
    url = "/personneViewer.jsp";
    DBCollection test = getSpecificCollection("Personne");
    System.out.println("Test.getCount");
    System.out.println(test.getCount());
    ArrayList<Map> test2 = fillSpecificCollection(test);
    request.setAttribute("prof", test2);
    }
     else if (type.equals("Batiment")) {
    url = "/personneViewer.jsp";
    DBCollection test = getSpecificCollection("Personne");
    System.out.println("Test.getCount");
    System.out.println(test.getCount());
    ArrayList<Map> test2 = fillSpecificCollection(test);
    request.setAttribute("prof", test2);
    }*/

    ServletContext sc = getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher(url);
    rd.forward(request, response);
}