List of usage examples for com.mongodb.client MongoCollection count
@Deprecated
long count();
From source file:com.imos.sample.SampleMongoDB.java
public static void main(String[] args) { MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017"); MongoClient mongoClient = new MongoClient(connectionString); MongoDatabase database = mongoClient.getDatabase("sampledb"); MongoCollection<Document> collection = database.getCollection("sampleLog"); System.out.println(collection.count()); MongoCursor<Document> cursor = collection.find().iterator(); ObjectMapper mapper = new ObjectMapper(); try {//from w w w .j a va 2 s .co m while (cursor.hasNext()) { try { System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next())); } catch (JsonProcessingException ex) { Logger.getLogger(SampleMongoDB.class.getName()).log(Level.SEVERE, null, ex); } } } finally { cursor.close(); } }
From source file:com.imos.sample.SampleMongoDB.java
private static void sampleOne(MongoDatabase database) throws JsonProcessingException { MongoCollection<Document> collection = database.getCollection("test"); Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1) .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6")) .append("info", new Document("x", 203).append("y", 102)); // collection.insertOne(doc); System.out.println(collection.count()); MongoCursor<Document> cursor = collection.find().iterator(); ObjectMapper mapper = new ObjectMapper(); // try { // while (cursor.hasNext()) { //// System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next())); // } // } finally { // cursor.close(); // }/* w w w. jav a2s. co m*/ Document myDoc = collection.find(eq("type", "database")).first(); System.out.println(myDoc.toJson()); }
From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java
License:Open Source License
@Override public String test() throws Exception { URI uri = new URI(getUrl()); StringBuilder sb = new StringBuilder(); if (!"mongodb".equals(uri.getScheme())) throw new SearchLibException( "Wrong scheme: " + uri.getScheme() + ". The URL should start with: mongodb://"); MongoClient mongoClient = null;/*from ww w . ja v a 2 s . co m*/ try { mongoClient = getMongoClient(); sb.append("Connection established."); sb.append(StringUtils.LF); if (!StringUtils.isEmpty(databaseName)) { MongoDatabase db = mongoClient.getDatabase(databaseName); if (db == null) throw new SearchLibException("Database not found: " + databaseName); MongoIterable<String> collections = db.listCollectionNames(); if (collections == null) throw new SearchLibException("No collection found."); sb.append("Collections found:"); sb.append(StringUtils.LF); for (String collection : collections) { sb.append(collection); sb.append(StringUtils.LF); } if (!StringUtils.isEmpty(collectionName)) { MongoCollection<?> dbCollection = db.getCollection(collectionName); if (dbCollection == null) throw new SearchLibException("Collection " + collectionName + " not found."); sb.append( "Collection " + collectionName + " contains " + dbCollection.count() + " document(s)."); sb.append(StringUtils.LF); if (!StringUtils.isEmpty(criteria)) { long count = dbCollection.count(getCriteriaObject()); sb.append("Query returns " + count + " document(s)."); sb.append(StringUtils.LF); } } } } finally { if (mongoClient != null) mongoClient.close(); } return sb.toString(); }
From source file:com.mycompany.megadatamongo.Main.java
public static void main(String[] args) throws IOException { Main app = new Main(); MongoCollection<Document> collection = app.db.getCollection("bigCollection"); // collection.insertOne(new Document("abcd", "{'name':'bla', 'con':'la'}")); app.gn.generate(collection, 500000000); System.out.println("Test: " + collection.count()); // BasicDBObject query = new BasicDBObject("abc", new BasicDBObject("$exists", true)); // /*from w w w . j a v a 2 s . c om*/ //// query.get("abcd"); // FindIterable<Document> docs = collection.find(query); // for (Document doc : docs) { // System.out.println("Doc: "+doc.toJson()); // } }
From source file:com.torodb.testing.mongodb.docker.ReplicaSetContract.java
License:Apache License
@Test default void genericTest() { int docsToInsert = 100; try (ReplicaSet replicaSet = getReplicaSet(simpleReplConfig())) { replicaSet.startAsync();//from w ww. j a va2 s .com replicaSet.awaitRunning(); getLogger().debug("Inserting {} documents on {}", docsToInsert, replicaSet.getReplSetName()); MongoDatabase db = replicaSet.getClient().getDatabase("testDb"); MongoCollection<Document> col = db.getCollection("testCol") .withWriteConcern(replicaSet.getTotalWriteConcern()); for (int i = 0; i < docsToInsert; i++) { col.insertOne(new Document()); } Assertions.assertEquals(docsToInsert, col.count()); for (ReplMongod mongo : replicaSet.getMongos()) { getLogger().debug("Assertions on node {}", mongo); long oplogCount = mongo.getMongoClient().getDatabase("local").getCollection("rs.oplog").count(); Assertions.assertNotEquals(0, oplogCount, "Oplog on node " + mongo + " is empty"); long colCount = mongo.getMongoClient().getDatabase("testDb").getCollection("testCol").count(); Assertions.assertEquals(docsToInsert, colCount, "Incorrect number of documents replicated"); } } }
From source file:com.torodb.testing.mongodb.docker.ShardedClusterContract.java
License:Apache License
@Test default void startAndStop() { try (ShardedCluster cluster = getShardedCluster(smallShardedClusterConfig())) { getLogger().debug("Starting cluster..."); cluster.startAsync();/* w ww.j a v a 2 s . c om*/ cluster.awaitRunning(); getLogger().debug("Cluster has been started"); getLogger().debug("Configuring cluster"); cluster.enableSharding("testDb"); cluster.shardCollection("testDb", "testCol"); cluster.setChunckSize(1); getLogger().debug("Sharding has been configured"); getLogger().debug("Inserting documents"); int docsToInsert = 10_000; MongoDatabase db = cluster.getClient().getDatabase("testDb"); MongoCollection<Document> col = db.getCollection("testCol"); for (int i = 0; i < docsToInsert; i++) { col.insertOne(new Document()); } getLogger().debug("Documents have been inserted"); Assertions.assertEquals(docsToInsert, col.count()); } }
From source file:com.twiceagain.handlers.logic.MyLogicHandlerInternal.java
License:Open Source License
public MyLogicHandlerInternal(PipedHttpHandler next, Map<String, Object> args) { super(next, args); System.out.printf("\n******Constructing %s with args = %s *******\n", this.getClass(), args); // Get client - mongo driver version 3.2 CLIENT = MongoDBClientSingleton.getInstance().getClient(); // Create auto-refreshing cache for the request CACHE = CacheFactory.createLocalLoadingCache(1, // cache size, Cache.EXPIRE_POLICY.AFTER_WRITE, 5000, // 5 seconds (String key) -> {//from ww w . j ava2 s . co m // Lamda to create content associated with key System.out.printf("\n*** Constructing cache for key = %s***", key); MongoCollection<Document> coll = CLIENT.getDatabase("auth").getCollection("users"); long nbusers = coll.count(); // Build Document for response Document doc = new Document("countOfUsersInDatabase", nbusers).append("another", new Document("mytest", new ArrayList<>())); // And save it to cache return doc; }); }
From source file:connector.DBConnector.java
public static int getNumberOfTwitterUsers() { MongoCollection<Document> coll = database.getCollection("tweets"); /*//from www . j av a 2s .co m Well, the root cause of the error here is because you have a String type as expected output and one of the distinct values is actually null. */ //Or accept the results as BsonValue and handle those: ArrayList<BsonValue> distinctUsers = coll.distinct("user", BsonValue.class).into(new ArrayList<>()); /* But in the latter case, you still need to handle the types returned. There are methods on BsonValue to allow you to code for this, but it is also a fair bit of overkill for just getting a list of distinct values. */ System.out.println("Collection size: " + coll.count()); System.out.println("Unique users: " + distinctUsers.size()); return distinctUsers.size(); }
From source file:controller.ProductController.java
public int getIndex() { Document doc = new Document(); MongoCollection<Document> col = db.getCollection("product"); if (col.count() <= 0) return 0; for (Document d : col.find()) doc = d;//from w w w .j a v a 2 s . c o m int j = (int) doc.get("itemId"); return j + 1; }
From source file:controller.UserController.java
public int getIndex() { Document doc = new Document(); MongoCollection<Document> col = db.getCollection("user"); if (col.count() <= 0) return 0; return (int) col.count(); // for(Document d: col.find()) doc = d; // int j =(int) doc.get("itemId"); // return j+1; }