List of usage examples for com.mongodb DBCollection getCount
public long getCount()
From source file:edu.csulaerp.db.ReferenceMongo.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args/*from w ww . jav a2s . com*/ * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public static void main(final String[] args) throws UnknownHostException { // connect to the local database server MongoClient mongoClient = new MongoClient(); /* // Authenticate - optional MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password); MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); */ // get handle to "mydb" DB db = mongoClient.getDB("mydb"); // get a list of the collections in this database and print them out Set<String> collectionNames = db.getCollectionNames(); for (final String s : collectionNames) { System.out.println(s); } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cursor = coll.find(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject("i", 71); cursor = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // $ Operators are represented as strings query = new BasicDBObject("j", new BasicDBObject("$ne", 3)).append("k", new BasicDBObject("$gt", 10)); cursor = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a range query to get a larger subset // find all where i > 50 query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); cursor = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); cursor = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // Count all documents in a collection but take a maximum second to do so coll.find().maxTime(1, SECONDS).count(); // Bulk operations BulkWriteOperation builder = coll.initializeOrderedBulkOperation(); builder.insert(new BasicDBObject("_id", 1)); builder.insert(new BasicDBObject("_id", 2)); builder.insert(new BasicDBObject("_id", 3)); builder.find(new BasicDBObject("_id", 1)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2))); builder.find(new BasicDBObject("_id", 2)).removeOne(); builder.find(new BasicDBObject("_id", 3)).replaceOne(new BasicDBObject("_id", 3).append("x", 4)); BulkWriteResult result = builder.execute(); System.out.println("Ordered bulk write result : " + result); // Unordered bulk operation - no guarantee of order of operation builder = coll.initializeUnorderedBulkOperation(); builder.find(new BasicDBObject("_id", 1)).removeOne(); builder.find(new BasicDBObject("_id", 2)).removeOne(); result = builder.execute(); System.out.println("Ordered bulk write result : " + result); // parallelScan ParallelScanOptions parallelScanOptions = ParallelScanOptions.builder().numCursors(3).batchSize(300) .build(); List<Cursor> cursors = coll.parallelScan(parallelScanOptions); for (Cursor pCursor : cursors) { while (pCursor.hasNext()) { System.out.println(pCursor.next()); } } // release resources db.dropDatabase(); mongoClient.close(); }
From source file:edu.sjsu.carbonated.client.MongoDBDOA.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.getDB("mydb"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get a list of the collections in this database and print them out Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);//from www .j a v a2s . c o m } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("test", new AlbumResource("name", "desc", "user", "asdf")); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); }
From source file:es.devcircus.mongodb_examples.hello_world.Main.java
License:Open Source License
/** * Mtodo que cuenta el nmero de documentos que hay en una coleccin * determinada de nuestra base de datos. */// w w w. ja v a2 s. c o m public static void countingDocumentsInACollection() { System.out.println(); System.out.println("---------------------------------------------------------------"); System.out.println(" Counting Documents in A Collection "); System.out.println("---------------------------------------------------------------"); System.out.println(); /*Counting Documents in A Collection Now that we've inserted 101 documents (the 100 we did in the loop, * plus the first one), we can check to see if we have them all using * the getCount() method.*/ DBCollection coll = db.getCollection(TEST_COLLECTION); System.out.println(" Nmero de documentos..: " + coll.getCount()); /*and it should print 101.*/ }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
/** * Counts the objects stored in a collection. * @param collection - collection whose objects are counted * @return the number of objects stored in the collection *//*from ww w . j a v a 2s . co m*/ public long count(final String collection) { checkArgument(isNotBlank(collection), "Uninitialized or invalid collection"); final DB db = client().getDB(CONFIG_MANAGER.getDbName()); final DBCollection dbcol = db.getCollection(collection); return dbcol.getCount(); }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
/** * Writes statistics about a collection to the specified output stream. * @param os - the output stream to write the statistics to * @param collection - collection from which the statistics are collected * @throws IOException - If an I/O error occurred *//*ww w.j a v a 2 s .c om*/ public void stats(final OutputStream os, final String collection) throws IOException { checkArgument(os != null, "Uninitialized output stream"); checkArgument(isNotBlank(collection), "Uninitialized or invalid collection"); final DB db = client().getDB(CONFIG_MANAGER.getDbName()); final DBCollection dbcol = db.getCollection(collection); try { os.write((" >> Collection: " + collection + "\n").getBytes()); final List<DBObject> indexes = dbcol.getIndexInfo(); os.write(" >> Indexes\n".getBytes()); for (final DBObject idx : indexes) { os.write((" " + idx.toString() + "\n").getBytes()); } os.write((" >> Items count: " + dbcol.getCount() + "\n").getBytes()); } finally { os.flush(); } }
From source file:example.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args/* w w w .j a v a2 s . c om*/ * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public static void main(final String[] args) throws UnknownHostException { // connect to the local database server MongoClient mongoClient = new MongoClient(); // get handle to "mydb" DB db = mongoClient.getDB("mydb"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get a list of the collections in this database and print them out Set<String> collectionNames = db.getCollectionNames(); for (final String s : collectionNames) { System.out.println(s); } // get a collection object to work with DBCollection testCollection = db.getCollection("testCollection"); // drop all the data in it testCollection.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); testCollection.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = testCollection.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { testCollection.insert(new BasicDBObject().append("i", i)); } System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount()); // lets get all the documents in the collection and print them out DBCursor cursor = testCollection.find(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject("i", 71); cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a range query to get a larger subset query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // create an index on the "i" field testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = testCollection.getIndexInfo(); for (final DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); // release resources mongoClient.close(); }
From source file:examples.QuickTour.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.getDB("mydb"); // Authenticate - optional boolean auth = db.authenticate("foo", new char[] { 'b', 'a', 'r' }); // get a list of the collections in this database and print them out Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);// ww w . j av a 2s . c o m } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); }
From source file:ezbake.locksmith.db.MongoDBService.java
License:Apache License
public long collectionCount(String collection) { DBCollection coll = db.getCollection(collection); return coll.getCount(); }
From source file:localdomain.localhost.MongoDbTroubleshooter.java
License:Open Source License
public void run() throws Exception { try (PrintWriter writer = new PrintWriter(System.out)) { MongoClientURI mongoClientUri = new MongoClientURI(uri); writer.println("" + "host=" + mongoClientUri.getHosts() + ",username=" + mongoClientUri.getUsername() + ",database=" + mongoClientUri.getDatabase() + ",collection=" + mongoClientUri.getCollection() + ""); writer.println();/*w w w . j av a2 s . c o m*/ writer.println(); writer.println("# MongoClient"); writer.println(); MongoClient mongoClient = new MongoClient(mongoClientUri); writer.println("" + mongoClient + ""); writer.println(); writer.println(); writer.println("# Databases"); writer.println(); try { List<String> databaseNames = mongoClient.getDatabaseNames(); for (String databaseName : databaseNames) { writer.println("* " + databaseName + (databaseName.equals(mongoClientUri.getDatabase()) ? " - default database" : "")); } } catch (Exception e) { writer.println("Could not list the databases of the MongoDB instance: '" + e.getMessage() + "'"); } writer.println(); writer.println(); writer.println("# Database"); writer.println(); DB db = mongoClient.getDB(mongoClientUri.getDatabase()); writer.println("DB: " + db.getName() + ""); writer.println(); writer.println(); writer.println("## Collections"); writer.println(); Set<String> myCollections = db.getCollectionNames(); if (myCollections.isEmpty()) { writer.println("NO COLLECTIONS!"); } else { for (String collection : myCollections) { DBCollection dbCollection = db.getCollection(collection); writer.println("* " + dbCollection.getName() + " - " + dbCollection.getCount() + " entries"); } } } }
From source file:localdomain.localhost.MyServlet.java
License:Apache License
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.println("<html>"); writer.println("<head><title>MyServlet</title></head>"); writer.println("<body><h1>MyServlet</h1>"); writer.println("<h2>MongoDB</h2>"); String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local"); MongoClient mongoClient = null;/*from w w w . j av a2 s . c o m*/ try { writer.println("<h4>MongoClientURI</h4>"); MongoClientURI uri = new MongoClientURI(uriAsString); writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database=" + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>"); writer.println("<h4>MongoClient</h4>"); mongoClient = new MongoClient(uri); writer.println("<p>" + mongoClient + "</p>"); writer.println("<h4>Databases</h4>"); try { List<String> databaseNames = mongoClient.getDatabaseNames(); writer.println("<ul>"); for (String databaseName : databaseNames) { writer.println("<li>" + databaseName + (databaseName.equals(uri.getDatabase()) ? " - default database" : "")); } writer.println("</ul>"); } catch (Exception e) { writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage() + "</code></p>"); } writer.println("<h4>Database</h4>"); DB db = mongoClient.getDB(uri.getDatabase()); writer.println("<p>DB: " + db.getName() + "</p>"); writer.println("<h4>Collections</h4>"); Set<String> myCollections = db.getCollectionNames(); if (myCollections.isEmpty()) { writer.println("<p>NO COLLECTIONS!</p>"); } else { writer.println("<ul>"); for (String collection : myCollections) { DBCollection dbCollection = db.getCollection(collection); writer.println( "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>"); } writer.println("</ul>"); } writer.println("<h4>Success!</h4>"); writer.println("SUCCESS to access the mongodb database"); } catch (Exception e) { writer.println("<code><pre>"); e.printStackTrace(writer); writer.println("</pre></code>"); e.printStackTrace(); } finally { if (mongoClient != null) { try { mongoClient.close(); } catch (Exception e) { e.printStackTrace(); } } } writer.println("</body></html>"); }