/codes/spring-tutorial-data/spring-tutorial-data-nosql/src/main/java/io/github/dunwu/springboot/data/db/mongo/QuickTour.java

https://github.com/dunwu/spring-tutorial · Java · 175 lines · 104 code · 38 blank · 33 comment · 8 complexity · 15971f35c462b8864bb210d30810b865 MD5 · raw file

  1. package io.github.dunwu.springboot.data.db.mongo;
  2. import com.mongodb.Block;
  3. import com.mongodb.MongoClient;
  4. import com.mongodb.MongoClientURI;
  5. import com.mongodb.client.MongoCollection;
  6. import com.mongodb.client.MongoCursor;
  7. import com.mongodb.client.MongoDatabase;
  8. import com.mongodb.client.model.*;
  9. import com.mongodb.client.result.DeleteResult;
  10. import com.mongodb.client.result.UpdateResult;
  11. import org.bson.Document;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import static com.mongodb.client.model.Filters.*;
  15. import static com.mongodb.client.model.Projections.excludeId;
  16. import static com.mongodb.client.model.Sorts.descending;
  17. /**
  18. * The QuickTour code example see: https://mongodb.github.io/mongo-java-driver/3.0/getting-started
  19. */
  20. public class QuickTour {
  21. /**
  22. * Run this main method to see the output of this quick example.
  23. * @param args takes an optional single argument for the connection string
  24. */
  25. public static void main(final String[] args) {
  26. MongoClient mongoClient;
  27. if (args.length == 0) {
  28. // connect to the local database server
  29. mongoClient = new MongoClient("localhost", 27017);
  30. } else {
  31. mongoClient = new MongoClient(new MongoClientURI(args[0]));
  32. }
  33. // get handle to "mydb" database
  34. MongoDatabase database = mongoClient.getDatabase("mydb");
  35. // get a handle to the "test" collection
  36. MongoCollection<Document> collection = database.getCollection("test");
  37. // drop all the data in it
  38. collection.drop();
  39. // make a document and insert it
  40. Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
  41. new Document("x", 203).append("y", 102));
  42. collection.insertOne(doc);
  43. // get it (since it's the only one in there since we dropped the rest earlier on)
  44. Document myDoc = collection.find().first();
  45. System.out.println(myDoc.toJson());
  46. // now, lets add lots of little documents to the collection so we can explore
  47. // queries and cursors
  48. List<Document> documents = new ArrayList<Document>();
  49. for (int i = 0; i < 100; i++) {
  50. documents.add(new Document("i", i));
  51. }
  52. collection.insertMany(documents);
  53. System.out.println("total # of documents after inserting 100 small ones (should be 101) " + collection.count());
  54. // find first
  55. myDoc = collection.find().first();
  56. System.out.println(myDoc.toJson());
  57. // lets get all the documents in the collection and print them out
  58. MongoCursor<Document> cursor = collection.find().iterator();
  59. try {
  60. while (cursor.hasNext()) {
  61. System.out.println(cursor.next().toJson());
  62. }
  63. } finally {
  64. cursor.close();
  65. }
  66. for (Document cur : collection.find()) {
  67. System.out.println(cur.toJson());
  68. }
  69. // now use a query to get 1 document out
  70. myDoc = collection.find(eq("i", 71)).first();
  71. System.out.println(myDoc.toJson());
  72. // now use a range query to get a larger subset
  73. cursor = collection.find(gt("i", 50)).iterator();
  74. try {
  75. while (cursor.hasNext()) {
  76. System.out.println(cursor.next().toJson());
  77. }
  78. } finally {
  79. cursor.close();
  80. }
  81. // range query with multiple constraints
  82. cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();
  83. try {
  84. while (cursor.hasNext()) {
  85. System.out.println(cursor.next().toJson());
  86. }
  87. } finally {
  88. cursor.close();
  89. }
  90. // Query Filters
  91. myDoc = collection.find(eq("i", 71)).first();
  92. System.out.println(myDoc.toJson());
  93. // now use a range query to get a larger subset
  94. Block<Document> printBlock = new Block<Document>() {
  95. @Override
  96. public void apply(final Document document) {
  97. System.out.println(document.toJson());
  98. }
  99. };
  100. collection.find(gt("i", 50)).forEach(printBlock);
  101. // filter where; 50 < i <= 100
  102. collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
  103. // Sorting
  104. myDoc = collection.find(exists("i")).sort(descending("i")).first();
  105. System.out.println(myDoc.toJson());
  106. // Projection
  107. myDoc = collection.find().projection(excludeId()).first();
  108. System.out.println(myDoc.toJson());
  109. // Update One
  110. collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));
  111. // Update Many
  112. UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100)));
  113. System.out.println(updateResult.getModifiedCount());
  114. // Delete One
  115. collection.deleteOne(eq("i", 110));
  116. // Delete Many
  117. DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
  118. System.out.println(deleteResult.getDeletedCount());
  119. collection.drop();
  120. // ordered bulk writes
  121. List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
  122. writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
  123. writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
  124. writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
  125. writes.add(new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
  126. writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
  127. writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));
  128. collection.bulkWrite(writes);
  129. collection.drop();
  130. collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
  131. // collection.find().forEach(printBlock);
  132. // Clean up
  133. database.drop();
  134. // release resources
  135. mongoClient.close();
  136. }
  137. }