diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index a867bad4c..00d663de9 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -14,6 +14,7 @@ import org.bson.Document; import java.util.Arrays; +import java.util.List; // end imports @@ -30,6 +31,8 @@ public static void main(String[] args) { // end connection collection.drop(); + + // Inserts sample documents describing restaurants // begin insert collection.insertMany(Arrays.asList( new Document("name", "Sun Bakery Trattoria").append("contact", new Document().append("phone", "386-555-0189").append("email", "SunBakeryTrattoria@example.org").append("location", Arrays.asList(-74.0056649, 40.7452371))).append("stars", 4).append("categories", Arrays.asList("Pizza", "Pasta", "Italian", "Coffee", "Sandwiches")), @@ -45,18 +48,21 @@ public static void main(String[] args) { )); // end insert + // Creates an aggregation pipeline that matches documents, groups them by the "stars" field, and tallies them by distinct values // begin aggregation one collection.aggregate( Arrays.asList( Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)) ) + // Prints the result of the aggregation operation as JSON ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one + // begin aggregation three Document explanation = collection.aggregate( Arrays.asList( - Aggregates.match(Filters.eq("categories", "bakery")), + Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)) ) ).explain(ExplainVerbosity.EXECUTION_STATS); @@ -64,6 +70,7 @@ public static void main(String[] args) { List stages = explanation.get("stages", List.class); List keys = Arrays.asList("queryPlanner", "winningPlan"); + // Prints the JSON representation of the winning execution plans for (Document stage : stages) { Document cursorStage = stage.get("$cursor", Document.class); if (cursorStage != null) { @@ -71,6 +78,7 @@ public static void main(String[] args) { } } // end aggregation three + // Prints the restaurant name and the first value in the "categories" array as a field named "firstCategory" // begin aggregation two collection.aggregate( Arrays.asList( diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java index 2a216caa5..52f806b73 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -77,17 +77,20 @@ private void insertExceptionExample() { // begin insertExceptionExample try { List> bulkOperations = new ArrayList<>(); - + + // Creates instructions to insert documents InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); bulkOperations.add(doc1); bulkOperations.add(doc3); + // Runs a bulk write operation for the specified insert WriteModels collection.bulkWrite(bulkOperations); + // Prints a message if any exceptions occur during the bulk write operation } catch (MongoBulkWriteException e){ - System.out.println("A MongoBulkWriteException occured with the following message: " + e.getMessage()); + System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); } //end insertExceptionExample } @@ -95,15 +98,21 @@ private void insertExceptionExample() { private void bulkWriteNotOrderedExample() { List> bulkOperations = new ArrayList<>(); - + // Creates instructions to insert a document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); + + // Creates instructions to replace the first document that matches the query ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); + .append("location", "Helena, MT")); + + // Creates instructions to update the first document that matches the query UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents that match the query DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -111,28 +120,33 @@ private void bulkWriteNotOrderedExample() { bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); - // begin bulkWriteNotOrderedExample BulkWriteOptions options = new BulkWriteOptions().ordered(false); + // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order collection.bulkWrite(bulkOperations, options); //end bulkWriteNotOrderedExample } private void bulkWriteExample() { // begin bulkWriteExample - List> bulkOperations = new ArrayList<>(); - + // Creates instructions to insert a document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); + .append("name", "Zaynab Omar") + .append("age", 37)); + + // Creates instructions to replace the first document matched by the query ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), - new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + new Document("name", "Sandy Kane") + .append("location", "Helena, MT")); + + // Creates instructions to update the first document matched by the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents matched by the query DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -140,6 +154,7 @@ private void bulkWriteExample() { bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); + // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order collection.bulkWrite(bulkOperations); //end bulkWriteExample } @@ -147,9 +162,11 @@ private void bulkWriteExample() { private void insertDocumentsExample(){ List> bulkOperations = new ArrayList<>(); + // Creates instructions to insert multiple documents // begin insertDocumentsExample InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") .append("age", 17)); + InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") .append("age", 22)); //end insertDocumentsExample @@ -157,12 +174,14 @@ private void insertDocumentsExample(){ bulkOperations.add(juneDoc); bulkOperations.add(kevinDoc); + // Runs a bulk write operation for the specified insert WriteModels collection.bulkWrite(bulkOperations); } private void replaceDocumentsExample(){ List> bulkOperations = new ArrayList<>(); + // Creates instructions to replace the first document matched by the query // begin replaceDocumentsExample ReplaceOneModel celineDoc = new ReplaceOneModel<>( Filters.eq("_id", 1), @@ -172,12 +191,14 @@ private void replaceDocumentsExample(){ bulkOperations.add(celineDoc); + // Runs a bulk write operation for the specified replace WriteModel collection.bulkWrite(bulkOperations); } private void updateDocumentsExample(){ List> bulkOperations = new ArrayList<>(); + // Creates instructions to update the first document matched by the query // begin updateDocumentsExample UpdateOneModel updateDoc = new UpdateOneModel<>( Filters.eq("_id", 2), @@ -186,18 +207,21 @@ private void updateDocumentsExample(){ bulkOperations.add(updateDoc); + // Runs a bulk write operation for the specified update WriteModel collection.bulkWrite(bulkOperations); } private void deleteDocumentsExample(){ List> bulkOperations = new ArrayList<>(); + // Creates instructions to delete the first document matched by the query // begin deleteDocumentsExample DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); //end deleteDocumentsExample bulkOperations.add(deleteDoc); + // Runs a bulk write operation for the specified delete WriteModel collection.bulkWrite(bulkOperations); } @@ -215,18 +239,19 @@ private void setUpCollection(){ InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) .append("name", "Karen Sandoval") .append("age", 31)); + InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) .append("name", "William Chin") .append("age", 54)); + InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) .append("name", "Shayla Ray") .append("age", 20)); - + bulkOperations.add(karen); bulkOperations.add(william); bulkOperations.add(shayla); - collection.bulkWrite(bulkOperations); } } diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 62314b21f..2a41372b5 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -34,12 +34,19 @@ public class CollationCollectionExample { private static void aggregatesExample(MongoCollection collection) { + // Creates aggregation stages to tally the frequencies of "first_name" values and sort the output documents // start aggregationExample Bson groupStage = Aggregates.group("$first_name", Accumulators.sum("nameCount", 1)); Bson sortStage = Aggregates.sort(Sorts.ascending("_id")); + AggregateIterable results = collection + // Runs the aggregation pipeline that includes tallying "first_name" frequencies .aggregate(Arrays.asList(groupStage, sortStage)) + + // Applies a collation to sort documents alphabetically by using the German locale, ignoring accents .collation(Collation.builder().locale("de").collationStrength(CollationStrength.PRIMARY).build()); + + // Prints the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -49,9 +56,13 @@ private static void aggregatesExample(MongoCollection collection) { private static void findAndSortExample(MongoCollection collection) { // start findAndSort List results = new ArrayList<>(); + + // Retrieves all documents and applies a "de@collation-phonebook" collation and ascending sort to the results collection.find() .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")).into(results); + + // Prints the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -59,6 +70,7 @@ private static void findAndSortExample(MongoCollection collection) { } private static void findOneAndUpdateExample(MongoCollection collection) { + // Updates the first matching document, sorted by using the "de@collation=phonebook" collation // start findOneAndUpdate Document result = collection.findOneAndUpdate( Filters.gt("first_name", "Gunter"), @@ -67,6 +79,8 @@ private static void findOneAndUpdateExample(MongoCollection collection .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")) .returnDocument(ReturnDocument.AFTER)); + + // Prints the JSON representation of the updated document if an update occurred if (result != null) { System.out.println("Updated document: " + result.toJson()); } @@ -74,11 +88,15 @@ private static void findOneAndUpdateExample(MongoCollection collection } private static void findOneAndDeleteExample(MongoCollection collection) { - List results = new ArrayList<>(); + + // Retrieves documents that match the filter and adds them to a list collection.find(Filters.gt("a", "100")).into(results); + + // Prints the JSON representation of the result list results.forEach(r -> System.out.println(r.toJson())); + // Deletes the first document that matches the filter, ordered by the value of the "a" field // start findOneAndDelete Document result = collection.findOneAndDelete( Filters.gt("a", "100"), @@ -89,6 +107,8 @@ private static void findOneAndDeleteExample(MongoCollection collection .numericOrdering(true) .build()) .sort(Sorts.ascending("a"))); + + // Prints the JSON representation of the deleted document if (result != null) { System.out.println("Deleted document: " + result.toJson()); } @@ -97,6 +117,7 @@ private static void findOneAndDeleteExample(MongoCollection collection private static void insertPhonebookDocuments(MongoCollection collection) { List docs = new ArrayList<>(); + docs.add(new Document("first_name", "Klara")); docs.add(new Document("first_name", "Gunter")); docs.add(new Document("first_name", "Günter")); @@ -108,6 +129,7 @@ private static void insertPhonebookDocuments(MongoCollection collection) { private static void insertNumericalStrings(MongoCollection collection) { List docs = new ArrayList<>(); + docs.add(new Document("_id", 1).append("a", "16 apples")); docs.add(new Document("_id", 2).append("a", "84 oranges")); docs.add(new Document("_id", 3).append("a", "179 bananas")); @@ -116,6 +138,7 @@ private static void insertNumericalStrings(MongoCollection collection) { } private static void collationBuilder() { + // Creates a collation that includes several collation options // start collationBuilder Collation.builder() .caseLevel(true) @@ -131,6 +154,7 @@ private static void collationBuilder() { } private static void createCollectionOptions(MongoDatabase database) { + // Creates a collection and sets its default collation locale as "en_US" // start createCollectionOptions database.createCollection( "items", @@ -142,9 +166,11 @@ private static void createCollectionOptions(MongoDatabase database) { private static void listIndexes(MongoDatabase database) { // start listIndexes MongoCollection collection = database.getCollection("items"); - List indexes = new ArrayList<>(); + collection.listIndexes().into(indexes); + + // Prints the collection's indexes and any default collations indexes.forEach(idx -> System.out.println(idx.toJson())); // end listIndexes } @@ -153,7 +179,11 @@ private static void createIndex(MongoDatabase database) { // start createIndex MongoCollection collection = database.getCollection("items"); IndexOptions idxOptions = new IndexOptions(); + + // Defines options that set a collation locale idxOptions.collation(Collation.builder().locale("en_US").build()); + + // Creates an index on the "name" field with the collation and ascending sort order collection.createIndex(Indexes.ascending("name"), idxOptions); // end createIndex } @@ -161,11 +191,16 @@ private static void createIndex(MongoDatabase database) { private static void createPhonebookIndex(MongoDatabase database) { MongoCollection collection = database.getCollection("phonebook"); IndexOptions idxOptions = new IndexOptions(); + + // Defines options that set a collation's locale, comparison levels, and punctuation guidelines idxOptions.collation(Collation.builder().locale("de@collation=search").collationStrength(CollationStrength.PRIMARY).collationAlternate(CollationAlternate.SHIFTED).build()); + + // Creates an index on the "first_name" field with the collation and ascending sort order collection.createIndex(Indexes.ascending("first_name"), idxOptions); } private static void indexOperation(MongoCollection collection) { + // Retrieves all documents and applies a collation and ascending sort to them // start indexOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("en_US").build()) @@ -175,6 +210,7 @@ private static void indexOperation(MongoCollection collection) { } private static void customCollationOperation(MongoCollection collection) { + // Retrieves all documents and applies a collation and ascending sort to them // start customCollationOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("is").build()) @@ -183,18 +219,20 @@ private static void customCollationOperation(MongoCollection collection) { } private static void operationCollation(MongoCollection collection) { + // Retrieves documents that match the query filter and applies a collation and ascending sort to the results // start operationCollation FindIterable cursor = collection.find(new Document("name", "cote")) .collation(Collation.builder().locale("en_US").build()) .sort(Sorts.ascending("name")); // end operationCollation + + // Prints the JSON representation of the returned documents cursor.forEach(doc -> System.out.println(doc.toJson())); } public static void main(String[] args) { String uri = ""; - try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("fundamentals_example"); diff --git a/source/includes/fundamentals/code-snippets/CompoundOperators.java b/source/includes/fundamentals/code-snippets/CompoundOperators.java index 1cf62850f..84b85c14a 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -30,10 +30,12 @@ public static void main(String[] args) throws InterruptedException { public static void runExample(boolean safe) throws InterruptedException { CompoundOperators.resetExample(); + Thread thread1; Thread thread2; String guest1 = "Jan"; String guest2 = "Pat"; + if (safe) { thread1 = new DemoClientSafe(guest1); thread2 = new DemoClientSafe(guest2); @@ -42,10 +44,12 @@ public static void runExample(boolean safe) throws InterruptedException { thread1 = new DemoClientUnsafe(guest1); thread2 = new DemoClientUnsafe(guest2); } + thread1.start(); thread2.start(); thread1.join(); thread2.join(); + CompoundOperators.whoGotTheRoom(); CompoundOperators.resetExample(); System.out.println("---------"); @@ -53,6 +57,7 @@ public static void runExample(boolean safe) throws InterruptedException { public static void whoGotTheRoom() { MongoCollection collection = CompoundOperators.getCollection(); + String guest = collection.find().first().get("guest", String.class); System.out.println("Only " + guest + " got the room"); } @@ -60,11 +65,13 @@ public static void whoGotTheRoom() { public static void resetExample() { MongoCollection collection = getCollection(); collection.deleteMany(new Document()); + + // Inserts a document representing an available room Document insert_room = new Document("_id", 1).append("reserved", false).append("guest", null).append("room", "Blue Room"); collection.insertOne(insert_room); } - public static MongoCollection getCollection(){ + public static MongoCollection getCollection() { String uri = System.getenv("DRIVER_URL"); MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase(DATABASE); @@ -107,16 +114,30 @@ class DemoClientUnsafe extends DemoClient { // start the-unsafe-book-a-room public void bookARoom() { + // Creates a filter to match documents representing available rooms Bson filter = Filters.eq("reserved", false); + + // Retrieves a document that represents the first available room Document myRoom = this.collection.find(filter).first(); + + // Prints a message if no documents representing available rooms are found if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } + String myRoomName = myRoom.getString("room"); + + // Prints a message that guest that successfully booked the room System.out.println("You got the " + myRoomName + " " + this.guest); + + // Creates an update document to mark a room as reserved Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); + + // Creates a filter that matches the "_id" field of the first available room Bson roomFilter = Filters.eq("_id", myRoom.get("_id", Integer.class)); + + // Updates the first matching document to mark it as reserved this.collection.updateOne(roomFilter, update); } // end the-unsafe-book-a-room @@ -137,13 +158,22 @@ class DemoClientSafe extends DemoClient { // start the-safe-book-a-room public void bookARoom(){ + // Creates an update document to mark a room as reserved Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); + + // Creates a filter to match a document representing an available room Bson filter = Filters.eq("reserved", false); + + // Updates the first document that matches the filter to mark it as reserved Document myRoom = this.collection.findOneAndUpdate(filter, update); + + // Prints a message when there are no available rooms if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } + + // Prints the name of the guest that successfully booked the room String myRoomName = myRoom.getString("room"); System.out.println("You got the " + myRoomName + " " + this.guest); } diff --git a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java index 381f62544..3102c5120 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java @@ -6,6 +6,9 @@ import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.*; import com.mongodb.client.result.InsertOneResult; + +import docs.builders.Filters; + import org.bson.Document; import org.bson.conversions.Bson; @@ -20,6 +23,7 @@ public class CompoundOperatorsIndividualExamples { public static void main(String[] args) throws InterruptedException { CompoundOperatorsIndividualExamples.resetExample(); CompoundOperatorsIndividualExamples examples = new CompoundOperatorsIndividualExamples(); + examples.findOneAndUpdateExample(); examples.findOneAndReplaceExample(); examples.findOneAndDeleteExample(); @@ -28,11 +32,14 @@ public static void main(String[] args) throws InterruptedException { public static void resetExample() { MongoCollection collection = getCollection(); collection.deleteMany(new Document()); + Document insert_pizza = new Document("_id", 1).append("food", "donut").append("color", "green"); Document insert_pear = new Document("_id", 2).append("food", "pear").append("color", "yellow"); ArrayList docs = new ArrayList(); docs.add(insert_pizza); docs.add(insert_pear); + + // Inserts sample documents describing food collection.insertMany(docs); } @@ -49,16 +56,26 @@ private void findOneAndUpdateExample() { MongoCollection collection = getCollection(); //start findOneAndUpdate-example // + + // Creates a projection to exclude the "_id" field from the retrieved documents Bson projection = Projections.excludeId(); + + // Creates a filter to match documents with a "color" value of "green" Bson filter = Filters.eq("color", "green"); + + // Creates an update document to set the value of "food" to "pizza" Bson update = Updates.set("food", "pizza"); + + // Defines options that specify projected fields, permit an upsert and limit execution time FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(). projection(projection). upsert(true). maxTime(5, TimeUnit.SECONDS); - /* The result variable contains your document in the - state before your update operation is performed. */ + + // Updates the first matching document with the content of the update document, applying the specified options Document result = collection.findOneAndUpdate(filter, update, options); + + // Prints the matched document in its state before the operation System.out.println(result.toJson()); //end findOneAndUpdate-example } @@ -69,9 +86,15 @@ private void findOneAndDeleteExample() { //start findOneAndDelete-example // Bson sort = Sorts.descending("_id"); + + // Creates an empty filter to match all documents in the collection Bson filter = Filters.empty(); + + // Defines options that specify a descending sort on the "_id" field FindOneAndDeleteOptions options = new FindOneAndDeleteOptions(). sort(sort); + + // Deletes the document containing the highest "_id" value and prints the deleted document Document result = collection.findOneAndDelete(filter, options); System.out.println(result.toJson()); //end findOneAndDelete-example @@ -83,10 +106,16 @@ private void findOneAndReplaceExample() { MongoCollection collection = getCollection(); //start findOneAndReplace-example // + + // Creates instructions to replace the matching document with a new document Bson filter = Filters.eq("color", "green"); Document replace = new Document("music", "classical").append("color", "green"); + + // Defines options specifying that the operation should return a document in its post-operation state FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(). returnDocument(ReturnDocument.AFTER); + + // Atomically finds and replaces the matching document and prints the replacement document Document result = collection.findOneAndReplace(filter, replace, options); System.out.println(result.toJson()); //end findOneAndReplace-example