List of usage examples for com.mongodb.client MongoCursor close
@Override
void close();
From source file:examples.tour.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 w w w. ja va2s .c o m*/ public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); // 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>() { 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()); // Aggregation collection .aggregate( asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))) .forEach(printBlock); myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), set("i", 110)); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("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:flipkart.mongo.replicator.node.ReplicationTask.java
License:Apache License
@Override public void run() { String shardId = rsConfig.shardName; Node masterNode = rsConfig.getMasterNode().get(); MongoClient client = MongoConnector.getMongoClient(Lists.newArrayList(masterNode)); MongoDatabase database = client.getDatabase("local"); lastCp = taskContext.checkPointHandler.getCheckPoint(shardId); logger.info(String.format("######## START REPLICATOR FOR MongoURI: %s. LastCheckpoint: %s #######", client.getAddress(), lastCp)); MongoCollection<Document> collection = database.getCollection("oplog.rs"); FindIterable<Document> iterable; MongoCursor<Document> cursor; do {/* w w w. j ava2 s . c o m*/ if (lastCp == null) { iterable = collection.find(); } else { iterable = collection.find(new Document("ts", new Document("$gt", lastCp))); } cursor = iterable.sort(new Document("$natural", 1)).noCursorTimeout(true) .cursorType(CursorType.TailableAwait).batchSize(3000).iterator(); try { executeCursor(cursor); Thread.sleep(WAIT_FOR_NEXT_ITERATION); } catch (MongoCursorNotFoundException e) { logger.info("Cursor has been closed. About to open a new cursor. ID: " + cursor.getServerCursor().getId()); } catch (Exception e) { logger.error("Exception while replicating", e); throw new RuntimeException(e); } finally { cursor.close(); } } while (true); }
From source file:foam.dao.MongoDAO.java
License:Open Source License
@Override public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) { sink = prepareSink(sink);//from www . ja v a 2 s . co m Sink decorated = decorateSink_(sink, skip, limit, order, predicate); Subscription sub = new Subscription(); Logger logger = (Logger) x.get("logger"); if (getOf() == null) { throw new IllegalArgumentException("`of` is not set"); } MongoCollection<BsonDocument> collection = database.getCollection(collectionName, BsonDocument.class); MongoCursor<BsonDocument> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { if (sub.getDetached()) break; FObject obj = createFObject(x, new BsonDocumentReader(cursor.next()), getOf().getObjClass(), logger); if ((predicate == null) || predicate.f(obj)) { decorated.put(obj, sub); } } } finally { cursor.close(); } decorated.eof(); return sink; }
From source file:fr.lirmm.graphik.graal.keyval.KeyValueStoreMongoDB.java
License:Open Source License
public void showCollection(MongoCollection<Document> col) { System.out.println(col.getNamespace().getCollectionName() + " : "); MongoCursor<Document> cursor = col.find().iterator(); try {/*w w w . ja v a2s. c om*/ while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } }
From source file:io.mandrel.blob.impl.MongoBlobStore.java
License:Apache License
@Override public void byPages(int pageSize, Callback callback) { MongoCursor<GridFSFile> cursor = bucket.find().iterator(); boolean loop = true; try {// w w w . j a v a2 s. c o m while (loop) { List<GridFSFile> files = new ArrayList<>(batchSize); int i = 0; while (cursor.hasNext() && i < batchSize) { files.add(cursor.next()); i++; } loop = callback.on(files.stream().map(file -> bucket.openDownloadStream(file.getObjectId())) .map(fromFile).collect(Collectors.toList())); } } finally { cursor.close(); } }
From source file:io.mandrel.document.impl.MongoDocumentStore.java
License:Apache License
@Override public void byPages(int pageSize, Callback callback) { MongoCursor<org.bson.Document> cursor = collection.find().iterator(); boolean loop = true; try {/*from w w w. j a va 2s .c o m*/ while (loop) { List<org.bson.Document> docs = new ArrayList<>(batchSize); int i = 0; while (cursor.hasNext() && i < batchSize) { docs.add(cursor.next()); i++; } loop = callback.on(docs.stream().map(fromBson).collect(Collectors.toList())); } } finally { cursor.close(); } }
From source file:io.mandrel.metadata.impl.MongoMetadataStore.java
License:Apache License
@Override public void byPages(int pageSize, Callback callback) { MongoCursor<org.bson.Document> cursor = collection.find().iterator(); boolean loop = true; try {/*from w w w . j a v a2s. com*/ while (loop) { List<org.bson.Document> docs = new ArrayList<>(batchSize); int i = 0; while (cursor.hasNext() && i < batchSize) { docs.add(cursor.next()); i++; } loop = callback.on(docs.stream().map(doc -> JsonBsonCodec.fromBson(mapper, doc, BlobMetadata.class)) .collect(Collectors.toList())); } } finally { cursor.close(); } }
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 {/*from w w w . j a v a 2s . com*/ 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 {// ww w.j a v a 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.ja va 2 s . 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 } }