List of usage examples for com.mongodb.client MongoCursor hasNext
@Override
boolean hasNext();
From source file:it.terrinoni.Controller.java
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("photo-sharing"); MongoCollection<Document> albums = database.getCollection("albums"); MongoCollection<Document> images = database.getCollection("images"); albums.createIndex(new Document("images", 1)); // Get the iterator of the whole collection MongoCursor<Document> cursor = images.find().iterator(); try {// w w w .ja va 2 s . co m while (cursor.hasNext()) { Document currImg = cursor.next(); Document foundImg = albums.find(eq("images", currImg.getDouble("_id"))).first(); if (foundImg == null) { //System.out.println(currImg.getDouble("_id") + " deleted."); images.deleteOne(currImg); } //System.out.println(currImg.getDouble("_id") + " is ok."); } } finally { cursor.close(); } long numImgs = images.count(eq("tags", "sunrises")); System.out.println("The total number of images with the tag \"sunrises\" after the removal of orphans is: " + String.valueOf(numImgs)); }
From source file:it.terrinoni.hw2.Homework.java
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("students"); MongoCollection<Document> collection = database.getCollection("grades"); Bson filter = eq("type", "homework"); Bson sort = ascending(asList("student_id", "score")); MongoCursor<Document> cursor = collection.find(filter).sort(sort).iterator(); double last_student_id = -1; try {// w ww.j ava 2 s. c om while (cursor.hasNext()) { Document doc = cursor.next(); if (doc.getDouble("student_id") != last_student_id) { last_student_id = doc.getDouble("student_id"); collection.deleteOne(doc); System.out.println("Document for " + last_student_id + " with score " + String.valueOf(doc.getDouble("score")) + " eliminated"); } Helpers.printJson(doc); } } finally { cursor.close(); } }
From source file:it.terrinoni.hw3.PruneHomeworks.java
public static void main(String[] args) { // MongoDB connection MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("school"); MongoCollection<Document> collection = database.getCollection("students"); // Get the cursor to the collection MongoCursor<Document> cursor = collection.find().iterator(); try {/* w w w . j a va2s . c o m*/ while (cursor.hasNext()) { // iteare over all the students double minScore = Double.MAX_VALUE; // set the maximum value Document minDoc = null; // temporary minimum Document student = cursor.next(); // current score // Retrieve the scores array List<Document> scores = student.get("scores", ArrayList.class); for (Document score : scores) { // iterate over the scores if (score.get("type", String.class).equals("homework")) { // get only the homeworks System.out.println("Student " + student.getDouble("_id") + " has homework score equals to " + score.getDouble("score")); // Update the minimum score if (score.getDouble("score") < minScore) { minScore = score.getDouble("score"); minDoc = score; } } } // Remove the minimum score scores.remove(minDoc); // Update the student document Bson filter = eq("_id", student.getDouble("_id")); Document update = new Document("$set", new Document("scores", scores)); collection.updateOne(filter, update); } } finally { cursor.close(); // close the cursos } }
From source file:joliex.mongodb.MongoDbConnector.java
@RequestResponse public Value listCollection() { Value v = Value.create();//from ww w .j ava 2s . c o m MongoIterable<String> listCollectionNames = db.listCollectionNames(); MongoCursor<String> iteratorListCollectionNames = listCollectionNames.iterator(); int counterCollection = 0; while (iteratorListCollectionNames.hasNext()) { String collection = iteratorListCollectionNames.next(); v.getChildren("collection").get(counterCollection).add(Value.create(collection)); counterCollection++; } return v; }
From source file:joliex.mongodb.MongoDbConnector.java
@RequestResponse public Value listDB() { Value v = Value.create();/*w ww . ja va 2s . c o m*/ MongoIterable<String> databaseNames = mongoClient.listDatabaseNames(); MongoCursor<String> databaseNamesIterator = databaseNames.iterator(); int counterDatabase = 0; while (databaseNamesIterator.hasNext()) { v.getChildren("db").get(counterDatabase).add(Value.create(databaseNamesIterator.next())); counterDatabase++; } return v; }
From source file:mongodb.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string *///from www. j a va 2 s. c o m public static void main(final String[] args) { //represents a pool of connections to the database MongoClient mongoClient = new MongoClient("10.9.17.105", 27017); // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("test"); // get a handle to the "test" collection MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); collection.find().forEach(printBlock); // Clean up // database.drop(); // release resources mongoClient.close(); }
From source file:mongoSample.MongoSample.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args//w ww.ja va2 s. co m * takes an optional single argument for the connection string */ public static void main(final String[] args) { String mongoServer = args[0]; MongoClient mongoClient = new MongoClient(mongoServer); MongoDatabase database = mongoClient.getDatabase("sakila"); MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest // earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can // explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); // collection.find().forEach(printBlock); // Clean up //database.drop(); // release resources mongoClient.close(); }
From source file:mongoSample.MyMongoDemo.java
License:Apache License
public static void main(final String[] args) { String mongoServer = args[0]; MongoClient mongoClient = new MongoClient(mongoServer); MongoDatabase database = mongoClient.getDatabase("NGDBDemo"); MongoCollection<Document> collection = database.getCollection("test"); collection.drop();//w w w. j a v a 2s .c om Document people = new Document(); // A document for a person people.put("Name", "Guy"); people.put("Email", "guy@gmail.com"); BasicDBList friendList = new BasicDBList(); // A list for the persons // friends BasicDBObject friendDoc = new BasicDBObject(); // A document for each // friend friendDoc.put("Name", "Jo"); friendDoc.put("Email", "Jo@gmail.com"); friendList.add(friendDoc); friendDoc.clear(); friendDoc.put("Name", "John"); friendDoc.put("Email", "john@gmail.com"); friendList.add(friendDoc); people.put("Friends", friendDoc); collection.insertOne(people); System.out.println('1'); MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } System.out.println('2'); for (Document cur : collection.find()) { System.out.println(cur.toJson()); } System.out.println('3'); // now use a query to get 1 document out Document myDoc = collection.find(eq("Name", "Guy")).first(); System.out.println(myDoc.toJson()); database = mongoClient.getDatabase("sakila"); collection = database.getCollection("films"); for (Document cur : collection.find()) { System.out.println(cur.toJson()); } mongoClient.close(); }
From source file:mongotweet.MongoTweet.java
public static void tweet(String uname, String tweet) { Random rand = new Random(); String id = "" + rand.nextInt(99999999); Document doc = new Document().append("tweet_id", id).append("username", uname).append("body", tweet); insertDocument("tweets", doc); doc = new Document().append("tweet_id", id).append("username", uname).append("time", System.currentTimeMillis()); insertDocument("timeline", doc); insertDocument("userline", doc); System.out.println(uname + ":" + tweet + " published"); MongoCollection coll = db.getCollection("followers"); BsonDocument where = new BsonDocument().append("username", new BsonString(uname)); MongoCursor<Document> cursor = coll.find(where).iterator(); String username;/*from www . ja va 2 s . c o m*/ while (cursor.hasNext()) { Document tmp = cursor.next(); username = (String) tmp.get("follower"); doc = new Document().append("tweet_id", id).append("username", username).append("time", System.currentTimeMillis()); insertDocument("timeline", doc); } }
From source file:mongotweet.MongoTweet.java
public static void showTweet(String uname) { MongoCollection coll = db.getCollection("tweets"); BsonDocument where = new BsonDocument().append("username", new BsonString(uname)); MongoCursor<Document> cursor = coll.find(where).iterator(); String username, body;//from w w w. j a va 2 s. co m while (cursor.hasNext()) { Document tmp = cursor.next(); username = (String) tmp.get("username"); body = (String) tmp.get("body"); System.out.format("%s : %s \n", username, body); } }