From ce57a6d25426de87b227610440d60564a8faa9d7 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 10 Oct 2023 14:35:56 -0400 Subject: [PATCH 01/10] DOCSP-33345: Java code comments pt. 4 --- .../fundamentals/code-snippets/AggTour.java | 14 +++- .../fundamentals/code-snippets/BulkWrite.java | 74 ++++++++++++++++--- .../CollationCollectionExample.java | 49 +++++++++++- .../code-snippets/CompoundOperators.java | 43 +++++++++++ .../CompoundOperatorsIndividualExamples.java | 31 +++++++- 5 files changed, 196 insertions(+), 15 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index a867bad4c..38e5f3520 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 @@ -24,12 +25,16 @@ public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string final String uri = ""; + // Create a client and access the "restaurants" collection in the "aggregation" database MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase("aggregation"); MongoCollection collection = database.getCollection("restaurants"); // end connection + // Drop the collection, if it exists, to ensure the collection initally does not contain any documents collection.drop(); + + // Insert sample restaurant documents // 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,6 +50,8 @@ public static void main(String[] args) { )); // end insert + // Filter for documents whose "categories" array field contains "Bakery" + // Then, group documents by the "stars" field and accumulate a count of distinct "stars" values // begin aggregation one collection.aggregate( Arrays.asList( @@ -53,17 +60,21 @@ public static void main(String[] args) { ) ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one + + // Use the "explain()" method to see the operation's execution plans and performance statistics // 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); + // Obtain the winning plans for aggregation stages that produce execution plans List stages = explanation.get("stages", List.class); List keys = Arrays.asList("queryPlanner", "winningPlan"); + // Print the JSON representation of the winning plans for (Document stage : stages) { Document cursorStage = stage.get("$cursor", Document.class); if (cursorStage != null) { @@ -71,6 +82,7 @@ public static void main(String[] args) { } } // end aggregation three + // Use a $project stage to return the "name" field and the calculated field "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..c5dc15b9e 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -30,12 +30,14 @@ public class BulkWrite { private BulkWrite() { final String uri = System.getenv("DRIVER_REF_URI"); + // Create a client and access the "bulkWrite" collection in the "crudOps" database mongoClient = MongoClients.create(uri); database = mongoClient.getDatabase("crudOps"); collection = database.getCollection("bulkWrite"); } public static void main(String[] args) { + // For each operation, set up the collection, run the operation, and print the results BulkWrite bulkWrite = new BulkWrite(); System.out.println("Ordered BulkWrite"); bulkWrite.setUpCollection(); @@ -76,16 +78,21 @@ public static void main(String[] args) { private void insertExceptionExample() { // begin insertExceptionExample try { + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); + // Create an InsertOneModel for two documents with ID values of 1 and 3 InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); + // Add the InsertOneModel instances to the bulkOperations list bulkOperations.add(doc1); bulkOperations.add(doc3); + // Run the bulk operations on your collection collection.bulkWrite(bulkOperations); + // Handle any exceptions that occur during the operations } catch (MongoBulkWriteException e){ System.out.println("A MongoBulkWriteException occured with the following message: " + e.getMessage()); } @@ -93,76 +100,102 @@ private void insertExceptionExample() { } private void bulkWriteNotOrderedExample() { + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - + // Create an InsertOneModel for a document with a "name" value of "Zaynab Omar" InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); + + // Create a ReplaceOneModel for a document with a "name" value of "Sandy Kane" ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); + .append("location", "Helena, MT")); + + // Create an UpdateOneModel to change the "name" value of a document UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); + + // Create a DeleteManyModel that matches documents with an "age" value greater than 50 DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + // Add each model instance to the bulkOperations list bulkOperations.add(insertDoc); bulkOperations.add(replaceDoc); bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); - + // Instruct the driver to execute the bulk operations in any order // begin bulkWriteNotOrderedExample BulkWriteOptions options = new BulkWriteOptions().ordered(false); + // Run the bulk operations on your collection with an options parameter collection.bulkWrite(bulkOperations, options); //end bulkWriteNotOrderedExample } private void bulkWriteExample() { + // Create a List that will store the bulk operations // begin bulkWriteExample - List> bulkOperations = new ArrayList<>(); + // Create an InsertOneModel for a document with a "name" value of "Zaynab Omar" InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); + .append("name", "Zaynab Omar") + .append("age", 37)); + + // Create a ReplaceOneModel for a document with a "name" value of "Sandy Kane" 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")); + + // Create an UpdateOneModel to change the "name" value of a document + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); + + // Create a DeleteManyModel that matches documents with an "age" value greater than 50 DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + // Add each model instance to the bulkOperations list bulkOperations.add(insertDoc); bulkOperations.add(replaceDoc); bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); + // Run the bulk operations on your collection collection.bulkWrite(bulkOperations); //end bulkWriteExample } private void insertDocumentsExample(){ + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); // begin insertDocumentsExample + // Create an InsertOneModel for a document with a "name" value of "June Carrie" InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") .append("age", 17)); + + // Create an InsertOneModel for a document with a "name" value of "Kevin Moss" InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") .append("age", 22)); //end insertDocumentsExample + // Add each model instance to the bulkOperations list bulkOperations.add(juneDoc); bulkOperations.add(kevinDoc); + // Run the bulk operations on your collection collection.bulkWrite(bulkOperations); } private void replaceDocumentsExample(){ + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); + // Create a ReplaceOneModel to replace a document with a "_id" value of 1 // begin replaceDocumentsExample ReplaceOneModel celineDoc = new ReplaceOneModel<>( Filters.eq("_id", 1), @@ -170,63 +203,82 @@ private void replaceDocumentsExample(){ .append("location", "San Diego, CA")); //end replaceDocumentsExample + // Add the ReplaceOneModel instance to the bulkOperations list bulkOperations.add(celineDoc); + // Run the replace operation on your collection collection.bulkWrite(bulkOperations); } private void updateDocumentsExample(){ + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); + // Create an UpdateOneModel to modify a document with a "_id" value of 2 // begin updateDocumentsExample UpdateOneModel updateDoc = new UpdateOneModel<>( Filters.eq("_id", 2), Updates.set("age", 31)); //end updateDocumentsExample + // Add the UpdateOneModel instance to the bulkOperations list bulkOperations.add(updateDoc); + // Run the update operation on your collection collection.bulkWrite(bulkOperations); } private void deleteDocumentsExample(){ + // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); + // Create a DeleteOneModel to delete a document with a "_id" value of 1 // begin deleteDocumentsExample DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); //end deleteDocumentsExample + // Add the DeleteOneModel instance to the bulkOperations list bulkOperations.add(deleteDoc); + // Run the delete operation on your collection collection.bulkWrite(bulkOperations); } private void preview(){ + // Print the JSON representation of the returned documents collection.find().forEach(doc -> System.out.println(doc.toJson())); } private void setUpCollection(){ + // Delete the collection so each operation starts with an empty collection collection.drop(); + // Create a List that will store the bulk operations //begin bulkOpsList List> bulkOperations = new ArrayList<>(); //end bulkOpsList + // Create an InsertOneModel for a document with a "name" value of "Karen Sandoval" InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) .append("name", "Karen Sandoval") .append("age", 31)); + + // Create an InsertOneModel for a document with a "name" value of "William Chin" InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) .append("name", "William Chin") .append("age", 54)); + + // Create an InsertOneModel for a document with a "name" value of "Shayla Ray" InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) .append("name", "Shayla Ray") .append("age", 20)); - + + // Add the model instances to the bulkOperations list bulkOperations.add(karen); bulkOperations.add(william); bulkOperations.add(shayla); - + // Run the bulk operations on your collection collection.bulkWrite(bulkOperations); } } diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 62314b21f..2e368b80f 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -35,11 +35,19 @@ public class CollationCollectionExample { private static void aggregatesExample(MongoCollection collection) { // start aggregationExample + // Specify the group aggregation stage to use each document's "first_name" value as the result's "_id" + // Then, sum the number of matching "first_name" values Bson groupStage = Aggregates.group("$first_name", Accumulators.sum("nameCount", 1)); + + // Specify the sort aggregation stage to sort by "_id" in ascending order Bson sortStage = Aggregates.sort(Sorts.ascending("_id")); + + // Construct a collation object with the German locale AggregateIterable results = collection .aggregate(Arrays.asList(groupStage, sortStage)) .collation(Collation.builder().locale("de").collationStrength(CollationStrength.PRIMARY).build()); + + // Print the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -47,11 +55,16 @@ private static void aggregatesExample(MongoCollection collection) { } private static void findAndSortExample(MongoCollection collection) { + // Create a List to store the result documents // start findAndSort List results = new ArrayList<>(); + + // Apply a collation specifying the German locale and "phonebook" variant on find operation results and sort collection.find() .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")).into(results); + + // Print the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -59,6 +72,7 @@ private static void findAndSortExample(MongoCollection collection) { } private static void findOneAndUpdateExample(MongoCollection collection) { + // Specify a collation on an operation that updates the first match of a "first_name" field query // start findOneAndUpdate Document result = collection.findOneAndUpdate( Filters.gt("first_name", "Gunter"), @@ -67,6 +81,8 @@ private static void findOneAndUpdateExample(MongoCollection collection .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")) .returnDocument(ReturnDocument.AFTER)); + + // Print the JSON representation of the results if (result != null) { System.out.println("Updated document: " + result.toJson()); } @@ -74,11 +90,16 @@ private static void findOneAndUpdateExample(MongoCollection collection } private static void findOneAndDeleteExample(MongoCollection collection) { - + // Create a List to store the result documents List results = new ArrayList<>(); + + // Find documents with an "a" value greater than 100 and store them in the results list collection.find(Filters.gt("a", "100")).into(results); + + // Print the JSON representation of the results results.forEach(r -> System.out.println(r.toJson())); + // Specify a numerical string ordering collation in an operation that deletes a query's first match // start findOneAndDelete Document result = collection.findOneAndDelete( Filters.gt("a", "100"), @@ -89,6 +110,8 @@ private static void findOneAndDeleteExample(MongoCollection collection .numericOrdering(true) .build()) .sort(Sorts.ascending("a"))); + + // Print the JSON representation of the deleted document if (result != null) { System.out.println("Deleted document: " + result.toJson()); } @@ -96,26 +119,35 @@ private static void findOneAndDeleteExample(MongoCollection collection } private static void insertPhonebookDocuments(MongoCollection collection) { + // Create a List to store a series of documents List docs = new ArrayList<>(); + + // Add documents with the "first_name" field to the docs list docs.add(new Document("first_name", "Klara")); docs.add(new Document("first_name", "Gunter")); docs.add(new Document("first_name", "Günter")); docs.add(new Document("first_name", "Jürgen")); docs.add(new Document("first_name", "Hannah")); + // Insert the documents into your collection collection.insertMany(docs); } private static void insertNumericalStrings(MongoCollection collection) { + // Create a List to store a series of documents List docs = new ArrayList<>(); + + // Add documents with an "a" field to the docs list 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")); + // Insert the documents into your collection collection.insertMany(docs); } private static void collationBuilder() { + // Use the Collation.Builder class to specify collation options // start collationBuilder Collation.builder() .caseLevel(true) @@ -131,6 +163,7 @@ private static void collationBuilder() { } private static void createCollectionOptions(MongoDatabase database) { + // Create a collection and specify the "en_US" locale collation // start createCollectionOptions database.createCollection( "items", @@ -140,18 +173,25 @@ private static void createCollectionOptions(MongoDatabase database) { } private static void listIndexes(MongoDatabase database) { + // Access the "items" collection // start listIndexes MongoCollection collection = database.getCollection("items"); + // Create a List to store the collection's indexes List indexes = new ArrayList<>(); + + // Retrieve a list of the collection's indexes to ensure the collation was successfully created collection.listIndexes().into(indexes); indexes.forEach(idx -> System.out.println(idx.toJson())); // end listIndexes } private static void createIndex(MongoDatabase database) { + // Access the "items" collection // start createIndex MongoCollection collection = database.getCollection("items"); + + // Create an index on the "name" field with the "en_US" locale collation in ascending order IndexOptions idxOptions = new IndexOptions(); idxOptions.collation(Collation.builder().locale("en_US").build()); collection.createIndex(Indexes.ascending("name"), idxOptions); @@ -159,7 +199,10 @@ private static void createIndex(MongoDatabase database) { } private static void createPhonebookIndex(MongoDatabase database) { + // Access the "phonebook" collection MongoCollection collection = database.getCollection("phonebook"); + + // Create an index on the "first_name" field with the "de@collation=search" locale collation in ascending order IndexOptions idxOptions = new IndexOptions(); idxOptions.collation(Collation.builder().locale("de@collation=search").collationStrength(CollationStrength.PRIMARY).collationAlternate(CollationAlternate.SHIFTED).build()); collection.createIndex(Indexes.ascending("first_name"), idxOptions); @@ -183,11 +226,14 @@ private static void customCollationOperation(MongoCollection collection) { } private static void operationCollation(MongoCollection collection) { + // Run a find operation that meets the criteria neccessary to use the "name" field index // start operationCollation FindIterable cursor = collection.find(new Document("name", "cote")) .collation(Collation.builder().locale("en_US").build()) .sort(Sorts.ascending("name")); // end operationCollation + + // Print the JSON representation of the returned documents cursor.forEach(doc -> System.out.println(doc.toJson())); } @@ -195,6 +241,7 @@ public static void main(String[] args) { String uri = ""; + // Create a client and access the "fundamentals_example" database 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..b14a729bf 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -21,6 +21,7 @@ public class CompoundOperators { * notified that they booked a room. */ public static void main(String[] args) throws InterruptedException { + // Run the compound operation examples and print the results System.out.println("\n---------"); System.out.println("Begin Unsafe Example:"); runExample(false); @@ -30,6 +31,8 @@ public static void main(String[] args) throws InterruptedException { public static void runExample(boolean safe) throws InterruptedException { CompoundOperators.resetExample(); + + // Create two threads representing guests Thread thread1; Thread thread2; String guest1 = "Jan"; @@ -42,29 +45,40 @@ public static void runExample(boolean safe) throws InterruptedException { thread1 = new DemoClientUnsafe(guest1); thread2 = new DemoClientUnsafe(guest2); } + + // Start the execution of the two threads thread1.start(); thread2.start(); thread1.join(); thread2.join(); + + // Determine who successfully booked the room CompoundOperators.whoGotTheRoom(); CompoundOperators.resetExample(); System.out.println("---------"); } public static void whoGotTheRoom() { + // Access the "compound-test" collection MongoCollection collection = CompoundOperators.getCollection(); + + // Retrieve and print the guest who successfully booked the room String guest = collection.find().first().get("guest", String.class); System.out.println("Only " + guest + " got the room"); } public static void resetExample() { + // Access the "compound-test" collection MongoCollection collection = getCollection(); + + // Clear any documents from the collection, then insert a document representing the "Blue Room" collection.deleteMany(new Document()); 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(){ + // Access the "compound-test" collection in the "test" database String uri = System.getenv("DRIVER_URL"); MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase(DATABASE); @@ -78,8 +92,11 @@ abstract class DemoClient extends Thread { String guest; MongoCollection collection; + // Constructor for initializing a client with a guest name DemoClient(String guest) { this.guest = guest; + + // Retrieve the collection used for booking this.collection = CompoundOperators.getCollection(); } @@ -101,22 +118,38 @@ public void bookARoom() { */ class DemoClientUnsafe extends DemoClient { + // Constructor for initializing an unsafe client with a guest name DemoClientUnsafe(String guest) { super(guest); } // start the-unsafe-book-a-room public void bookARoom() { + // Define a filter to find an available room Bson filter = Filters.eq("reserved", false); + + // Attempt to find the first available room Document myRoom = this.collection.find(filter).first(); + + // If no available rooms were found, print a message informing the guest if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } + + // Get the name of the available room String myRoomName = myRoom.getString("room"); + + // Inform the guest that they successfully booked the room System.out.println("You got the " + myRoomName + " " + this.guest); + + // Prepare an update to mark the room as reserved with the guest's name Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); + + // Define a filter to update the room that will be reserved Bson roomFilter = Filters.eq("_id", myRoom.get("_id", Integer.class)); + + // Perform the update operation to mark the room as reserved this.collection.updateOne(roomFilter, update); } // end the-unsafe-book-a-room @@ -131,19 +164,29 @@ public void bookARoom() { */ class DemoClientSafe extends DemoClient { + // Constructor for initializing a safe client with a guest name DemoClientSafe(String guest) { super(guest); } // start the-safe-book-a-room public void bookARoom(){ + // Prepare an update operation that will mark an available room as reserved Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); + + // Define a filter to find an available room Bson filter = Filters.eq("reserved", false); + + // Atomically find an available room and mark it as reserved Document myRoom = this.collection.findOneAndUpdate(filter, update); + + // If no available rooms were found, print a message informing the guest if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } + + // Get the name of the available room and inform the guest they've reserved 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..1fd37828b 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java @@ -20,14 +20,19 @@ public class CompoundOperatorsIndividualExamples { public static void main(String[] args) throws InterruptedException { CompoundOperatorsIndividualExamples.resetExample(); CompoundOperatorsIndividualExamples examples = new CompoundOperatorsIndividualExamples(); + + // Run each compound operation example examples.findOneAndUpdateExample(); examples.findOneAndReplaceExample(); examples.findOneAndDeleteExample(); } public static void resetExample() { + // Retrieve the "compound-ops" collection and delete its documents MongoCollection collection = getCollection(); collection.deleteMany(new Document()); + + // Insert documents describing food into the collection 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(); @@ -37,6 +42,7 @@ public static void resetExample() { } public static MongoCollection getCollection() { + // Access the "compound-test" collection in the "test" database String uri = System.getenv("DRIVER_URL"); MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase(DATABASE); @@ -49,15 +55,21 @@ private void findOneAndUpdateExample() { MongoCollection collection = getCollection(); //start findOneAndUpdate-example // + // Define a projection to exclude the "_id" field from the result Bson projection = Projections.excludeId(); + + // Define a filter to find documents with "color" field value of "green" Bson filter = Filters.eq("color", "green"); + + // Define an update operation to set the "food" field value to "pizza" Bson update = Updates.set("food", "pizza"); + + // Define options for the findOneAndUpdate operation 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. */ + // Run the operation and store your document in its state before the update operation Document result = collection.findOneAndUpdate(filter, update, options); System.out.println(result.toJson()); //end findOneAndUpdate-example @@ -68,10 +80,18 @@ private void findOneAndDeleteExample() { MongoCollection collection = getCollection(); //start findOneAndDelete-example // + + // Specify a descending sort on the "_id" field. Bson sort = Sorts.descending("_id"); + + // Define an empty filter to match all documents in the collection Bson filter = Filters.empty(); + + // Define options to apply the descending sort to the findOneAndDelete operation FindOneAndDeleteOptions options = new FindOneAndDeleteOptions(). sort(sort); + + // Run the operation and print the deleted document Document result = collection.findOneAndDelete(filter, options); System.out.println(result.toJson()); //end findOneAndDelete-example @@ -83,10 +103,17 @@ private void findOneAndReplaceExample() { MongoCollection collection = getCollection(); //start findOneAndReplace-example // + // Define a filter to match documents with a "color" field value of "green" Bson filter = Filters.eq("color", "green"); + + // Create a document that will replace an existing document in the collection Document replace = new Document("music", "classical").append("color", "green"); + + // Instruct the driver to return the document in its post-replace operation state FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(). returnDocument(ReturnDocument.AFTER); + + // Run the operation and print the replacement document Document result = collection.findOneAndReplace(filter, replace, options); System.out.println(result.toJson()); //end findOneAndReplace-example From e9bc6dfb03bf150e1d95406a17606e5c6205f1fa Mon Sep 17 00:00:00 2001 From: norareidy Date: Thu, 12 Oct 2023 17:41:27 -0400 Subject: [PATCH 02/10] bulkwrite CC feedback --- .../fundamentals/code-snippets/BulkWrite.java | 76 ++++++------------- 1 file changed, 24 insertions(+), 52 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java index c5dc15b9e..dc65c2c6f 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -30,14 +30,12 @@ public class BulkWrite { private BulkWrite() { final String uri = System.getenv("DRIVER_REF_URI"); - // Create a client and access the "bulkWrite" collection in the "crudOps" database mongoClient = MongoClients.create(uri); database = mongoClient.getDatabase("crudOps"); collection = database.getCollection("bulkWrite"); } public static void main(String[] args) { - // For each operation, set up the collection, run the operation, and print the results BulkWrite bulkWrite = new BulkWrite(); System.out.println("Ordered BulkWrite"); bulkWrite.setUpCollection(); @@ -78,21 +76,17 @@ public static void main(String[] args) { private void insertExceptionExample() { // begin insertExceptionExample try { - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - - // Create an InsertOneModel for two documents with ID values of 1 and 3 InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); - // Add the InsertOneModel instances to the bulkOperations list bulkOperations.add(doc1); bulkOperations.add(doc3); - // Run the bulk operations on your collection + // Runs write operations on the insert WriteModels collection.bulkWrite(bulkOperations); - // Handle any exceptions that occur during the operations + // Prints a message if any exceptions occur during the operations } catch (MongoBulkWriteException e){ System.out.println("A MongoBulkWriteException occured with the following message: " + e.getMessage()); } @@ -100,102 +94,92 @@ private void insertExceptionExample() { } private void bulkWriteNotOrderedExample() { - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - // Create an InsertOneModel for a document with a "name" value of "Zaynab Omar" + // Creates instructions to insert a new document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); - // Create a ReplaceOneModel for a document with a "name" value of "Sandy Kane" + // Creates instructions to replace the matching document ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), new Document("name", "Sandy Kane") .append("location", "Helena, MT")); - // Create an UpdateOneModel to change the "name" value of a document + // Creates instructions to update the matching document UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); - // Create a DeleteManyModel that matches documents with an "age" value greater than 50 + // Creates instructions to delete the matching document DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - // Add each model instance to the bulkOperations list bulkOperations.add(insertDoc); bulkOperations.add(replaceDoc); bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); - // Instruct the driver to execute the bulk operations in any order // begin bulkWriteNotOrderedExample BulkWriteOptions options = new BulkWriteOptions().ordered(false); - // Run the bulk operations on your collection with an options parameter + // Runs write operations on the insert, replace, update, and delete WriteModels in any order collection.bulkWrite(bulkOperations, options); //end bulkWriteNotOrderedExample } private void bulkWriteExample() { - // Create a List that will store the bulk operations // begin bulkWriteExample List> bulkOperations = new ArrayList<>(); - - // Create an InsertOneModel for a document with a "name" value of "Zaynab Omar" + // Creates instructions to insert a new document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); - // Create a ReplaceOneModel for a document with a "name" value of "Sandy Kane" + // Creates instructions to replace the matching document ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), new Document("name", "Sandy Kane") .append("location", "Helena, MT")); - // Create an UpdateOneModel to change the "name" value of a document + // Creates instructions to update the matching document UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); - // Create a DeleteManyModel that matches documents with an "age" value greater than 50 + // Creates instructions to delete the matching document DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - // Add each model instance to the bulkOperations list bulkOperations.add(insertDoc); bulkOperations.add(replaceDoc); bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); - // Run the bulk operations on your collection + // Runs write operations on the insert, replace, update, and delete WriteModels in order collection.bulkWrite(bulkOperations); //end bulkWriteExample } private void insertDocumentsExample(){ - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); + // Creates instructions to insert two new documents // begin insertDocumentsExample - // Create an InsertOneModel for a document with a "name" value of "June Carrie" InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") .append("age", 17)); - - // Create an InsertOneModel for a document with a "name" value of "Kevin Moss" + InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") .append("age", 22)); //end insertDocumentsExample - // Add each model instance to the bulkOperations list bulkOperations.add(juneDoc); bulkOperations.add(kevinDoc); - // Run the bulk operations on your collection + // Runs write operations on the insert WriteModels collection.bulkWrite(bulkOperations); } private void replaceDocumentsExample(){ - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - // Create a ReplaceOneModel to replace a document with a "_id" value of 1 + // Creates instructions to replace the matching document // begin replaceDocumentsExample ReplaceOneModel celineDoc = new ReplaceOneModel<>( Filters.eq("_id", 1), @@ -203,82 +187,70 @@ private void replaceDocumentsExample(){ .append("location", "San Diego, CA")); //end replaceDocumentsExample - // Add the ReplaceOneModel instance to the bulkOperations list bulkOperations.add(celineDoc); - // Run the replace operation on your collection + // Runs the write operation on the replace WriteModel collection.bulkWrite(bulkOperations); } private void updateDocumentsExample(){ - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - // Create an UpdateOneModel to modify a document with a "_id" value of 2 + // Creates instructions to update the matching document // begin updateDocumentsExample UpdateOneModel updateDoc = new UpdateOneModel<>( Filters.eq("_id", 2), Updates.set("age", 31)); //end updateDocumentsExample - // Add the UpdateOneModel instance to the bulkOperations list bulkOperations.add(updateDoc); - // Run the update operation on your collection + // Runs the write operation on the update WriteModel collection.bulkWrite(bulkOperations); } private void deleteDocumentsExample(){ - // Create a List that will store the bulk operations List> bulkOperations = new ArrayList<>(); - // Create a DeleteOneModel to delete a document with a "_id" value of 1 + // Creates instructions to delete the matching document // begin deleteDocumentsExample DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); //end deleteDocumentsExample - // Add the DeleteOneModel instance to the bulkOperations list bulkOperations.add(deleteDoc); - // Run the delete operation on your collection + // Runs the write operation on the delete WriteModel collection.bulkWrite(bulkOperations); } private void preview(){ - // Print the JSON representation of the returned documents + // Prints the JSON representation of each document in the collection collection.find().forEach(doc -> System.out.println(doc.toJson())); } private void setUpCollection(){ - // Delete the collection so each operation starts with an empty collection collection.drop(); - // Create a List that will store the bulk operations //begin bulkOpsList List> bulkOperations = new ArrayList<>(); //end bulkOpsList - // Create an InsertOneModel for a document with a "name" value of "Karen Sandoval" InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) .append("name", "Karen Sandoval") .append("age", 31)); - - // Create an InsertOneModel for a document with a "name" value of "William Chin" + InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) .append("name", "William Chin") .append("age", 54)); - - // Create an InsertOneModel for a document with a "name" value of "Shayla Ray" + InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) .append("name", "Shayla Ray") .append("age", 20)); - // Add the model instances to the bulkOperations list bulkOperations.add(karen); bulkOperations.add(william); bulkOperations.add(shayla); - // Run the bulk operations on your collection collection.bulkWrite(bulkOperations); } } From b001ba680f27fc81c8928c436fab61e10ea5d900 Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Oct 2023 14:16:24 -0400 Subject: [PATCH 03/10] applying CC feedback --- .../fundamentals/code-snippets/AggTour.java | 14 ++-- .../CollationCollectionExample.java | 65 ++++++++----------- .../code-snippets/CompoundOperators.java | 49 ++++++-------- .../CompoundOperatorsIndividualExamples.java | 34 ++++------ 4 files changed, 65 insertions(+), 97 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index 38e5f3520..8ec86dc52 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -25,16 +25,14 @@ public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string final String uri = ""; - // Create a client and access the "restaurants" collection in the "aggregation" database MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase("aggregation"); MongoCollection collection = database.getCollection("restaurants"); // end connection - // Drop the collection, if it exists, to ensure the collection initally does not contain any documents collection.drop(); - // Insert sample restaurant documents + // 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")), @@ -50,8 +48,7 @@ public static void main(String[] args) { )); // end insert - // Filter for documents whose "categories" array field contains "Bakery" - // Then, group documents by the "stars" field and accumulate a count of distinct "stars" values + // Groups matching documents by the "stars" field and accumulates a count of distinct "stars" values // begin aggregation one collection.aggregate( Arrays.asList( @@ -61,7 +58,7 @@ public static void main(String[] args) { ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one - // Use the "explain()" method to see the operation's execution plans and performance statistics + // Outputs the operation's winning and rejected execution plans // begin aggregation three Document explanation = collection.aggregate( Arrays.asList( @@ -70,11 +67,10 @@ public static void main(String[] args) { ) ).explain(ExplainVerbosity.EXECUTION_STATS); - // Obtain the winning plans for aggregation stages that produce execution plans List stages = explanation.get("stages", List.class); List keys = Arrays.asList("queryPlanner", "winningPlan"); - // Print the JSON representation of the winning plans + // Prints the JSON representation of the winning execution plans for (Document stage : stages) { Document cursorStage = stage.get("$cursor", Document.class); if (cursorStage != null) { @@ -82,7 +78,7 @@ public static void main(String[] args) { } } // end aggregation three - // Use a $project stage to return the "name" field and the calculated field "firstCategory" + // Prints the "name" field and the calculated field "firstCategory" // begin aggregation two collection.aggregate( Arrays.asList( diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 2e368b80f..dc5006dd4 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -34,20 +34,17 @@ public class CollationCollectionExample { private static void aggregatesExample(MongoCollection collection) { + // Creates instructions to calculate the frequency of "first_name" values // start aggregationExample - // Specify the group aggregation stage to use each document's "first_name" value as the result's "_id" - // Then, sum the number of matching "first_name" values Bson groupStage = Aggregates.group("$first_name", Accumulators.sum("nameCount", 1)); - - // Specify the sort aggregation stage to sort by "_id" in ascending order Bson sortStage = Aggregates.sort(Sorts.ascending("_id")); - // Construct a collation object with the German locale + // Constructs a collation object with the German locale that ignores accents AggregateIterable results = collection .aggregate(Arrays.asList(groupStage, sortStage)) .collation(Collation.builder().locale("de").collationStrength(CollationStrength.PRIMARY).build()); - // Print the JSON representation of the results + // Prints the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -55,16 +52,15 @@ private static void aggregatesExample(MongoCollection collection) { } private static void findAndSortExample(MongoCollection collection) { - // Create a List to store the result documents // start findAndSort List results = new ArrayList<>(); - // Apply a collation specifying the German locale and "phonebook" variant on find operation results and sort + // Runs a find operation and applies a collation to the sorted results collection.find() .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")).into(results); - // Print the JSON representation of the results + // Prints the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -72,7 +68,7 @@ private static void findAndSortExample(MongoCollection collection) { } private static void findOneAndUpdateExample(MongoCollection collection) { - // Specify a collation on an operation that updates the first match of a "first_name" field query + // Runs an operation that updates the first matching document with a new "verified" field // start findOneAndUpdate Document result = collection.findOneAndUpdate( Filters.gt("first_name", "Gunter"), @@ -82,7 +78,7 @@ private static void findOneAndUpdateExample(MongoCollection collection .sort(Sorts.ascending("first_name")) .returnDocument(ReturnDocument.AFTER)); - // Print the JSON representation of the results + // Prints the JSON representation of the results if (result != null) { System.out.println("Updated document: " + result.toJson()); } @@ -90,16 +86,15 @@ private static void findOneAndUpdateExample(MongoCollection collection } private static void findOneAndDeleteExample(MongoCollection collection) { - // Create a List to store the result documents List results = new ArrayList<>(); - // Find documents with an "a" value greater than 100 and store them in the results list + // Runs a find operation and stores matching documents in a list collection.find(Filters.gt("a", "100")).into(results); - // Print the JSON representation of the results + // Prints the JSON representation of the result list results.forEach(r -> System.out.println(r.toJson())); - // Specify a numerical string ordering collation in an operation that deletes a query's first match + // Runs a delete operation specifying a numerical string ordering collation // start findOneAndDelete Document result = collection.findOneAndDelete( Filters.gt("a", "100"), @@ -111,7 +106,7 @@ private static void findOneAndDeleteExample(MongoCollection collection .build()) .sort(Sorts.ascending("a"))); - // Print the JSON representation of the deleted document + // Prints the JSON representation of the deleted document if (result != null) { System.out.println("Deleted document: " + result.toJson()); } @@ -119,35 +114,31 @@ private static void findOneAndDeleteExample(MongoCollection collection } private static void insertPhonebookDocuments(MongoCollection collection) { - // Create a List to store a series of documents List docs = new ArrayList<>(); - // Add documents with the "first_name" field to the docs list docs.add(new Document("first_name", "Klara")); docs.add(new Document("first_name", "Gunter")); docs.add(new Document("first_name", "Günter")); docs.add(new Document("first_name", "Jürgen")); docs.add(new Document("first_name", "Hannah")); - // Insert the documents into your collection + // Inserts the sample documents into a collection collection.insertMany(docs); } private static void insertNumericalStrings(MongoCollection collection) { - // Create a List to store a series of documents List docs = new ArrayList<>(); - // Add documents with an "a" field to the docs list 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")); - // Insert the documents into your collection + // Inserts the sample documents into a collection collection.insertMany(docs); } private static void collationBuilder() { - // Use the Collation.Builder class to specify collation options + // Creates collation instructions that specify all possible collation options // start collationBuilder Collation.builder() .caseLevel(true) @@ -163,7 +154,7 @@ private static void collationBuilder() { } private static void createCollectionOptions(MongoDatabase database) { - // Create a collection and specify the "en_US" locale collation + // Creates a collection and sets its default collation locale as "en_US" // start createCollectionOptions database.createCollection( "items", @@ -173,42 +164,41 @@ private static void createCollectionOptions(MongoDatabase database) { } private static void listIndexes(MongoDatabase database) { - // Access the "items" collection // start listIndexes MongoCollection collection = database.getCollection("items"); - - // Create a List to store the collection's indexes List indexes = new ArrayList<>(); - // Retrieve a list of the collection's indexes to ensure the collation was successfully created collection.listIndexes().into(indexes); + + // Prints a list of the collection's indexes to ensure successful collation creation indexes.forEach(idx -> System.out.println(idx.toJson())); // end listIndexes } private static void createIndex(MongoDatabase database) { - // Access the "items" collection // start createIndex MongoCollection collection = database.getCollection("items"); - - // Create an index on the "name" field with the "en_US" locale collation in ascending order IndexOptions idxOptions = new IndexOptions(); idxOptions.collation(Collation.builder().locale("en_US").build()); + + // Creates an index on the "name" field with a collation and ascending sort order collection.createIndex(Indexes.ascending("name"), idxOptions); // end createIndex } private static void createPhonebookIndex(MongoDatabase database) { - // Access the "phonebook" collection MongoCollection collection = database.getCollection("phonebook"); - - // Create an index on the "first_name" field with the "de@collation=search" locale collation in ascending order IndexOptions idxOptions = new IndexOptions(); + + // Specifies collation options that set punctuation guidelines, comparison levels, and locale 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 collection.createIndex(Indexes.ascending("first_name"), idxOptions); } private static void indexOperation(MongoCollection collection) { + // Runs a find operation and applies a collation and ascending sort to the results // start indexOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("en_US").build()) @@ -218,6 +208,7 @@ private static void indexOperation(MongoCollection collection) { } private static void customCollationOperation(MongoCollection collection) { + // Runs a find operation and applies a collation and ascending sort to the results // start customCollationOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("is").build()) @@ -226,22 +217,20 @@ private static void customCollationOperation(MongoCollection collection) { } private static void operationCollation(MongoCollection collection) { - // Run a find operation that meets the criteria neccessary to use the "name" field index + // Runs a find operation that meets the criteria for using the "name" field index // start operationCollation FindIterable cursor = collection.find(new Document("name", "cote")) .collation(Collation.builder().locale("en_US").build()) .sort(Sorts.ascending("name")); // end operationCollation - // Print the JSON representation of the returned documents + // Prints the JSON representation of the returned documents cursor.forEach(doc -> System.out.println(doc.toJson())); } public static void main(String[] args) { String uri = ""; - - // Create a client and access the "fundamentals_example" database 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 b14a729bf..c2466123d 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -21,7 +21,6 @@ public class CompoundOperators { * notified that they booked a room. */ public static void main(String[] args) throws InterruptedException { - // Run the compound operation examples and print the results System.out.println("\n---------"); System.out.println("Begin Unsafe Example:"); runExample(false); @@ -32,11 +31,12 @@ public static void main(String[] args) throws InterruptedException { public static void runExample(boolean safe) throws InterruptedException { CompoundOperators.resetExample(); - // Create two threads representing guests Thread thread1; Thread thread2; String guest1 = "Jan"; String guest2 = "Pat"; + + // Creates two threads representing guests if (safe) { thread1 = new DemoClientSafe(guest1); thread2 = new DemoClientSafe(guest2); @@ -46,39 +46,36 @@ public static void runExample(boolean safe) throws InterruptedException { thread2 = new DemoClientUnsafe(guest2); } - // Start the execution of the two threads + // Starts the execution of the two threads thread1.start(); thread2.start(); thread1.join(); thread2.join(); - // Determine who successfully booked the room + // Determines who successfully booked the room CompoundOperators.whoGotTheRoom(); CompoundOperators.resetExample(); System.out.println("---------"); } public static void whoGotTheRoom() { - // Access the "compound-test" collection MongoCollection collection = CompoundOperators.getCollection(); - // Retrieve and print the guest who successfully booked the room + // Retrieves and prints the guest who successfully booked the room String guest = collection.find().first().get("guest", String.class); System.out.println("Only " + guest + " got the room"); } public static void resetExample() { - // Access the "compound-test" collection MongoCollection collection = getCollection(); - - // Clear any documents from the collection, then insert a document representing the "Blue Room" collection.deleteMany(new Document()); + + // Creates and 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(){ - // Access the "compound-test" collection in the "test" database + public static MongoCollection getCollection() { String uri = System.getenv("DRIVER_URL"); MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase(DATABASE); @@ -92,11 +89,8 @@ abstract class DemoClient extends Thread { String guest; MongoCollection collection; - // Constructor for initializing a client with a guest name DemoClient(String guest) { this.guest = guest; - - // Retrieve the collection used for booking this.collection = CompoundOperators.getCollection(); } @@ -118,38 +112,36 @@ public void bookARoom() { */ class DemoClientUnsafe extends DemoClient { - // Constructor for initializing an unsafe client with a guest name DemoClientUnsafe(String guest) { super(guest); } // start the-unsafe-book-a-room public void bookARoom() { - // Define a filter to find an available room + // Creates a filter to match documents representing available rooms Bson filter = Filters.eq("reserved", false); - // Attempt to find the first available room + // Runs a find operation to match the first available room Document myRoom = this.collection.find(filter).first(); - // If no available rooms were found, print a message informing the guest + // Prints a message if no documents representing available rooms are found if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } - // Get the name of the available room String myRoomName = myRoom.getString("room"); - // Inform the guest that they successfully booked the room + // Prints a message that guest that successfully booked the room System.out.println("You got the " + myRoomName + " " + this.guest); - // Prepare an update to mark the room as reserved with the guest's name + // Creates update instructions to mark a room as reserved Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); - // Define a filter to update the room that will be reserved + // Creates a filter to match the document representing a specific room Bson roomFilter = Filters.eq("_id", myRoom.get("_id", Integer.class)); - // Perform the update operation to mark the room as reserved + // Runs an update operation to mark the matched document as representing a reserved room this.collection.updateOne(roomFilter, update); } // end the-unsafe-book-a-room @@ -164,29 +156,28 @@ public void bookARoom() { */ class DemoClientSafe extends DemoClient { - // Constructor for initializing a safe client with a guest name DemoClientSafe(String guest) { super(guest); } // start the-safe-book-a-room public void bookARoom(){ - // Prepare an update operation that will mark an available room as reserved + // Creates update instructions to mark a room as reserved Bson update = Updates.combine(Updates.set("reserved", true), Updates.set("guest", guest)); - // Define a filter to find an available room + // Creates a filter to match a document representing an available room Bson filter = Filters.eq("reserved", false); - // Atomically find an available room and mark it as reserved + // Finds a matching document atomically and updates a field value to reflect its reserved status Document myRoom = this.collection.findOneAndUpdate(filter, update); - // If no available rooms were found, print a message informing the guest + // Prints a message if no documents representing available rooms are found if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } - // Get the name of the available room and inform the guest they've reserved the room + // Prints a message that 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 1fd37828b..29605a64f 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java @@ -21,28 +21,26 @@ public static void main(String[] args) throws InterruptedException { CompoundOperatorsIndividualExamples.resetExample(); CompoundOperatorsIndividualExamples examples = new CompoundOperatorsIndividualExamples(); - // Run each compound operation example examples.findOneAndUpdateExample(); examples.findOneAndReplaceExample(); examples.findOneAndDeleteExample(); } public static void resetExample() { - // Retrieve the "compound-ops" collection and delete its documents MongoCollection collection = getCollection(); collection.deleteMany(new Document()); - // Insert documents describing food into the collection 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 documents describing food into the collection collection.insertMany(docs); } public static MongoCollection getCollection() { - // Access the "compound-test" collection in the "test" database String uri = System.getenv("DRIVER_URL"); MongoClient mongoClient = MongoClients.create(uri); MongoDatabase database = mongoClient.getDatabase(DATABASE); @@ -55,22 +53,22 @@ private void findOneAndUpdateExample() { MongoCollection collection = getCollection(); //start findOneAndUpdate-example // - // Define a projection to exclude the "_id" field from the result Bson projection = Projections.excludeId(); - // Define a filter to find documents with "color" field value of "green" + // Creates instructions to modify the "food" value of the matching document Bson filter = Filters.eq("color", "green"); - - // Define an update operation to set the "food" field value to "pizza" Bson update = Updates.set("food", "pizza"); - // Define options for the findOneAndUpdate operation + // 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); - // Run the operation and store your document in its state before the update operation + + // Runs the update operation and applies the operation instructions 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 } @@ -80,18 +78,14 @@ private void findOneAndDeleteExample() { MongoCollection collection = getCollection(); //start findOneAndDelete-example // - - // Specify a descending sort on the "_id" field. Bson sort = Sorts.descending("_id"); - - // Define an empty filter to match all documents in the collection Bson filter = Filters.empty(); - // Define options to apply the descending sort to the findOneAndDelete operation + // Defines options that specify a descending sort on the "_id" field FindOneAndDeleteOptions options = new FindOneAndDeleteOptions(). sort(sort); - // Run the operation and print the deleted document + // Runs the operation and prints the deleted document Document result = collection.findOneAndDelete(filter, options); System.out.println(result.toJson()); //end findOneAndDelete-example @@ -103,17 +97,15 @@ private void findOneAndReplaceExample() { MongoCollection collection = getCollection(); //start findOneAndReplace-example // - // Define a filter to match documents with a "color" field value of "green" + // Creates instructions to replace the matching document with a new document Bson filter = Filters.eq("color", "green"); - - // Create a document that will replace an existing document in the collection Document replace = new Document("music", "classical").append("color", "green"); - // Instruct the driver to return the document in its post-replace operation state + // Defines options specifying that the document is returned in its post-operation state FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(). returnDocument(ReturnDocument.AFTER); - // Run the operation and print the replacement document + // Runs the operation and prints the replacement document Document result = collection.findOneAndReplace(filter, replace, options); System.out.println(result.toJson()); //end findOneAndReplace-example From b6290a7bca5ff4e24900e53793acf361b74f78f9 Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Oct 2023 14:19:34 -0400 Subject: [PATCH 04/10] small edit --- source/includes/fundamentals/code-snippets/AggTour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index 8ec86dc52..16ab17da2 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -78,7 +78,7 @@ public static void main(String[] args) { } } // end aggregation three - // Prints the "name" field and the calculated field "firstCategory" + // Prints the documents' "name" values and the values of a new "firstCategory" field // begin aggregation two collection.aggregate( Arrays.asList( From a748ddfd7f40f75fe39ebca8d810c35a3d2a754e Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 17 Oct 2023 10:04:41 -0400 Subject: [PATCH 05/10] half of feedback --- .../fundamentals/code-snippets/AggTour.java | 9 ++++++--- .../fundamentals/code-snippets/BulkWrite.java | 19 +++++++++---------- .../CollationCollectionExample.java | 10 ++++++---- 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index 16ab17da2..171eb0b15 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -48,17 +48,20 @@ public static void main(String[] args) { )); // end insert - // Groups matching documents by the "stars" field and accumulates a count of distinct "stars" values // begin aggregation one collection.aggregate( Arrays.asList( + // Creates instructions to match documents that contain the "Bakery" category Aggregates.match(Filters.eq("categories", "Bakery")), + + // Creates instructions to group documents by the "stars" field and tally them by distinct values Aggregates.group("$stars", Accumulators.sum("count", 1)) ) + + // Prints the result of the aggregation pipeline ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one - // Outputs the operation's winning and rejected execution plans // begin aggregation three Document explanation = collection.aggregate( Arrays.asList( @@ -78,7 +81,7 @@ public static void main(String[] args) { } } // end aggregation three - // Prints the documents' "name" values and the values of a new "firstCategory" field + // 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 dc65c2c6f..841884ca5 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -83,7 +83,7 @@ private void insertExceptionExample() { bulkOperations.add(doc1); bulkOperations.add(doc3); - // Runs write operations on the insert WriteModels + // Runs a bulk write operation for the specified insert WriteModels collection.bulkWrite(bulkOperations); // Prints a message if any exceptions occur during the operations @@ -106,11 +106,11 @@ private void bulkWriteNotOrderedExample() { new Document("name", "Sandy Kane") .append("location", "Helena, MT")); - // Creates instructions to update the matching document + // 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 the matching document + // Creates instructions to delete all matching documents DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -121,7 +121,7 @@ private void bulkWriteNotOrderedExample() { // begin bulkWriteNotOrderedExample BulkWriteOptions options = new BulkWriteOptions().ordered(false); - // Runs write operations on the insert, replace, update, and delete WriteModels in any order + // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order collection.bulkWrite(bulkOperations, options); //end bulkWriteNotOrderedExample } @@ -130,7 +130,7 @@ private void bulkWriteExample() { // begin bulkWriteExample List> bulkOperations = new ArrayList<>(); - // Creates instructions to insert a new document + // Creates instructions to insert a document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); @@ -144,7 +144,7 @@ private void bulkWriteExample() { UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); - // Creates instructions to delete the matching document + // Creates instructions to delete all matching documents DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -152,7 +152,7 @@ private void bulkWriteExample() { bulkOperations.add(updateDoc); bulkOperations.add(deleteDoc); - // Runs write operations on the insert, replace, update, and delete WriteModels in order + // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order collection.bulkWrite(bulkOperations); //end bulkWriteExample } @@ -160,7 +160,7 @@ private void bulkWriteExample() { private void insertDocumentsExample(){ List> bulkOperations = new ArrayList<>(); - // Creates instructions to insert two new documents + // Creates instructions to insert multiple documents // begin insertDocumentsExample InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") .append("age", 17)); @@ -172,7 +172,7 @@ private void insertDocumentsExample(){ bulkOperations.add(juneDoc); bulkOperations.add(kevinDoc); - // Runs write operations on the insert WriteModels + // Runs a bulk write operation for the specified insert WriteModels collection.bulkWrite(bulkOperations); } @@ -224,7 +224,6 @@ private void deleteDocumentsExample(){ } private void preview(){ - // Prints the JSON representation of each document in the collection collection.find().forEach(doc -> System.out.println(doc.toJson())); } diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index dc5006dd4..5269e8ff7 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -34,17 +34,19 @@ public class CollationCollectionExample { private static void aggregatesExample(MongoCollection collection) { - // Creates instructions to calculate the frequency of "first_name" values + // Runs an aggregation pipeline to tally the frequencies of "first_name" values // start aggregationExample Bson groupStage = Aggregates.group("$first_name", Accumulators.sum("nameCount", 1)); Bson sortStage = Aggregates.sort(Sorts.ascending("_id")); - // Constructs a collation object with the German locale that ignores accents 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 + // Prints the results of the aggregation that tallied value frequencies and sorted the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -55,7 +57,7 @@ private static void findAndSortExample(MongoCollection collection) { // start findAndSort List results = new ArrayList<>(); - // Runs a find operation and applies a collation to the sorted results + // Retrieves all documents and sorts by the "first_name" values by using the "de@collation-phonebook" collation collection.find() .collation(Collation.builder().locale("de@collation=phonebook").build()) .sort(Sorts.ascending("first_name")).into(results); From 3630611f7e509de61e8201d04742315d86679cf5 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 17 Oct 2023 14:00:05 -0400 Subject: [PATCH 06/10] rest of feedback --- .../fundamentals/code-snippets/BulkWrite.java | 12 +++++---- .../CollationCollectionExample.java | 26 +++++++++---------- .../code-snippets/CompoundOperators.java | 22 +++++++--------- .../CompoundOperatorsIndividualExamples.java | 17 ++++++++---- 4 files changed, 41 insertions(+), 36 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java index 841884ca5..b6c047138 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -77,6 +77,8 @@ 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)); @@ -88,7 +90,7 @@ private void insertExceptionExample() { // Prints a message if any exceptions occur during the operations } 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 } @@ -96,7 +98,7 @@ private void insertExceptionExample() { private void bulkWriteNotOrderedExample() { List> bulkOperations = new ArrayList<>(); - // Creates instructions to insert a new document + // Creates instructions to insert a document InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) .append("name", "Zaynab Omar") .append("age", 37)); @@ -189,7 +191,7 @@ private void replaceDocumentsExample(){ bulkOperations.add(celineDoc); - // Runs the write operation on the replace WriteModel + // Runs a bulk write operation for the specified replace WriteModel collection.bulkWrite(bulkOperations); } @@ -205,7 +207,7 @@ private void updateDocumentsExample(){ bulkOperations.add(updateDoc); - // Runs the write operation on the update WriteModel + // Runs a bulk write operation for the specified update WriteModel collection.bulkWrite(bulkOperations); } @@ -219,7 +221,7 @@ private void deleteDocumentsExample(){ bulkOperations.add(deleteDoc); - // Runs the write operation on the delete WriteModel + // Runs a bulk write operation for the specified delete WriteModel collection.bulkWrite(bulkOperations); } diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 5269e8ff7..4ebf764bb 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -34,7 +34,7 @@ public class CollationCollectionExample { private static void aggregatesExample(MongoCollection collection) { - // Runs an aggregation pipeline to tally the frequencies of "first_name" values + // 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")); @@ -70,7 +70,7 @@ private static void findAndSortExample(MongoCollection collection) { } private static void findOneAndUpdateExample(MongoCollection collection) { - // Runs an operation that updates the first matching document with a new "verified" field + // Updates the first matching document, sorted by using the "de@collation=phonebook" collation // start findOneAndUpdate Document result = collection.findOneAndUpdate( Filters.gt("first_name", "Gunter"), @@ -80,7 +80,7 @@ private static void findOneAndUpdateExample(MongoCollection collection .sort(Sorts.ascending("first_name")) .returnDocument(ReturnDocument.AFTER)); - // Prints the JSON representation of the results + // Prints the JSON representation of the updated document, if an update occurred if (result != null) { System.out.println("Updated document: " + result.toJson()); } @@ -90,13 +90,13 @@ private static void findOneAndUpdateExample(MongoCollection collection private static void findOneAndDeleteExample(MongoCollection collection) { List results = new ArrayList<>(); - // Runs a find operation and stores matching documents in a list + // Finds documents that match the filter and stores the matches in 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())); - // Runs a delete operation specifying a numerical string ordering collation + // 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"), @@ -124,7 +124,6 @@ private static void insertPhonebookDocuments(MongoCollection collection) { docs.add(new Document("first_name", "Jürgen")); docs.add(new Document("first_name", "Hannah")); - // Inserts the sample documents into a collection collection.insertMany(docs); } @@ -135,12 +134,11 @@ private static void insertNumericalStrings(MongoCollection collection) { docs.add(new Document("_id", 2).append("a", "84 oranges")); docs.add(new Document("_id", 3).append("a", "179 bananas")); - // Inserts the sample documents into a collection collection.insertMany(docs); } private static void collationBuilder() { - // Creates collation instructions that specify all possible collation options + // Creates a collation that includes several collation options // start collationBuilder Collation.builder() .caseLevel(true) @@ -172,7 +170,7 @@ private static void listIndexes(MongoDatabase database) { collection.listIndexes().into(indexes); - // Prints a list of the collection's indexes to ensure successful collation creation + // Prints the collection's indexes and any default collations indexes.forEach(idx -> System.out.println(idx.toJson())); // end listIndexes } @@ -181,6 +179,8 @@ private static void createIndex(MongoDatabase database) { // start createIndex MongoCollection collection = database.getCollection("items"); IndexOptions idxOptions = new IndexOptions(); + + // Specifies collation options to set a locale idxOptions.collation(Collation.builder().locale("en_US").build()); // Creates an index on the "name" field with a collation and ascending sort order @@ -192,15 +192,15 @@ private static void createPhonebookIndex(MongoDatabase database) { MongoCollection collection = database.getCollection("phonebook"); IndexOptions idxOptions = new IndexOptions(); - // Specifies collation options that set punctuation guidelines, comparison levels, and locale + // Specifies collation options that set a 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 + // 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) { - // Runs a find operation and applies a collation and ascending sort to the results + // Retrieves all documents and applies a collation and ascending sort to these documents // start indexOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("en_US").build()) @@ -210,7 +210,7 @@ private static void indexOperation(MongoCollection collection) { } private static void customCollationOperation(MongoCollection collection) { - // Runs a find operation and applies a collation and ascending sort to the results + // Retrieves all documents and applies a collation and ascending sort to these documents // start customCollationOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("is").build()) diff --git a/source/includes/fundamentals/code-snippets/CompoundOperators.java b/source/includes/fundamentals/code-snippets/CompoundOperators.java index c2466123d..154f70c10 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -36,7 +36,6 @@ public static void runExample(boolean safe) throws InterruptedException { String guest1 = "Jan"; String guest2 = "Pat"; - // Creates two threads representing guests if (safe) { thread1 = new DemoClientSafe(guest1); thread2 = new DemoClientSafe(guest2); @@ -46,13 +45,11 @@ public static void runExample(boolean safe) throws InterruptedException { thread2 = new DemoClientUnsafe(guest2); } - // Starts the execution of the two threads thread1.start(); thread2.start(); thread1.join(); thread2.join(); - // Determines who successfully booked the room CompoundOperators.whoGotTheRoom(); CompoundOperators.resetExample(); System.out.println("---------"); @@ -61,7 +58,6 @@ public static void runExample(boolean safe) throws InterruptedException { public static void whoGotTheRoom() { MongoCollection collection = CompoundOperators.getCollection(); - // Retrieves and prints the guest who successfully booked the room String guest = collection.find().first().get("guest", String.class); System.out.println("Only " + guest + " got the room"); } @@ -70,7 +66,7 @@ public static void resetExample() { MongoCollection collection = getCollection(); collection.deleteMany(new Document()); - // Creates and inserts a document representing an available room + // 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); } @@ -121,7 +117,7 @@ public void bookARoom() { // Creates a filter to match documents representing available rooms Bson filter = Filters.eq("reserved", false); - // Runs a find operation to match the first available room + // Finds the first available room Document myRoom = this.collection.find(filter).first(); // Prints a message if no documents representing available rooms are found @@ -135,13 +131,13 @@ public void bookARoom() { // Prints a message that guest that successfully booked the room System.out.println("You got the " + myRoomName + " " + this.guest); - // Creates update instructions to mark a room as reserved + // 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 the document representing a specific room + // Creates a filter that matches the "_id" field of the first available room Bson roomFilter = Filters.eq("_id", myRoom.get("_id", Integer.class)); - // Runs an update operation to mark the matched document as representing a reserved room + // Updates the first matching document to mark it as reserved this.collection.updateOne(roomFilter, update); } // end the-unsafe-book-a-room @@ -162,22 +158,22 @@ class DemoClientSafe extends DemoClient { // start the-safe-book-a-room public void bookARoom(){ - // Creates update instructions to mark a room as reserved + // 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); - // Finds a matching document atomically and updates a field value to reflect its reserved status + // Atomically finds and updates a document to mark it as reserved Document myRoom = this.collection.findOneAndUpdate(filter, update); - // Prints a message if no documents representing available rooms are found + // Prints a message when there are no available rooms if (myRoom == null){ System.out.println("Sorry, we are booked " + this.guest); return; } - // Prints a message that guest that successfully booked the room + // 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 29605a64f..bb39d68f2 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; @@ -36,7 +39,7 @@ public static void resetExample() { docs.add(insert_pizza); docs.add(insert_pear); - // Inserts documents describing food into the collection + // Inserts sample documents describing food collection.insertMany(docs); } @@ -53,10 +56,14 @@ private void findOneAndUpdateExample() { MongoCollection collection = getCollection(); //start findOneAndUpdate-example // + + // Configures a projection to exclude the "_id" field from the printed documents Bson projection = Projections.excludeId(); - // Creates instructions to modify the "food" value of the matching document + // Defines 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 @@ -65,7 +72,7 @@ private void findOneAndUpdateExample() { upsert(true). maxTime(5, TimeUnit.SECONDS); - // Runs the update operation and applies the operation instructions + // 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 @@ -101,11 +108,11 @@ private void findOneAndReplaceExample() { Bson filter = Filters.eq("color", "green"); Document replace = new Document("music", "classical").append("color", "green"); - // Defines options specifying that the document is returned in its post-operation state + // Defines options specifying that the operation should return a document in its post-operation state FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(). returnDocument(ReturnDocument.AFTER); - // Runs the operation and prints the replacement document + // 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 From 2ae0dc9a17b2731fb040acbf496f4515e9d9c9d1 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 17 Oct 2023 14:18:19 -0400 Subject: [PATCH 07/10] single line comment --- source/includes/fundamentals/code-snippets/AggTour.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index 171eb0b15..6926b3f3e 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -48,16 +48,13 @@ 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( - // Creates instructions to match documents that contain the "Bakery" category Aggregates.match(Filters.eq("categories", "Bakery")), - - // Creates instructions to group documents by the "stars" field and tally them by distinct values Aggregates.group("$stars", Accumulators.sum("count", 1)) ) - // Prints the result of the aggregation pipeline ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one From e6c270b55caef1ccf339a23d72f8b40561ed6746 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 17 Oct 2023 14:55:02 -0400 Subject: [PATCH 08/10] duplicate comments sheet suggestions --- .../fundamentals/code-snippets/AggTour.java | 2 +- .../code-snippets/CollationCollectionExample.java | 14 +++++++------- .../code-snippets/CompoundOperators.java | 4 ++-- .../CompoundOperatorsIndividualExamples.java | 9 ++++++--- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index 6926b3f3e..f6aebd15e 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -55,7 +55,7 @@ public static void main(String[] args) { Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)) ) - // Prints the result of the aggregation pipeline + // Prints the result of the aggregation pipeline as JSON ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 4ebf764bb..9fae6d99a 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -57,7 +57,7 @@ private static void findAndSortExample(MongoCollection collection) { // start findAndSort List results = new ArrayList<>(); - // Retrieves all documents and sorts by the "first_name" values by using the "de@collation-phonebook" collation + // 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); @@ -90,7 +90,7 @@ private static void findOneAndUpdateExample(MongoCollection collection private static void findOneAndDeleteExample(MongoCollection collection) { List results = new ArrayList<>(); - // Finds documents that match the filter and stores the matches in a list + // 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 @@ -180,10 +180,10 @@ private static void createIndex(MongoDatabase database) { MongoCollection collection = database.getCollection("items"); IndexOptions idxOptions = new IndexOptions(); - // Specifies collation options to set a locale + // Defines options that set a collation locale idxOptions.collation(Collation.builder().locale("en_US").build()); - // Creates an index on the "name" field with a collation and ascending sort order + // Creates an index on the "name" field with the collation and ascending sort order collection.createIndex(Indexes.ascending("name"), idxOptions); // end createIndex } @@ -192,7 +192,7 @@ private static void createPhonebookIndex(MongoDatabase database) { MongoCollection collection = database.getCollection("phonebook"); IndexOptions idxOptions = new IndexOptions(); - // Specifies collation options that set a locale, comparison levels, and punctuation guidelines + // 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 @@ -200,7 +200,7 @@ private static void createPhonebookIndex(MongoDatabase database) { } private static void indexOperation(MongoCollection collection) { - // Retrieves all documents and applies a collation and ascending sort to these documents + // 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()) @@ -210,7 +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 these documents + // Retrieves all documents and applies a collation and ascending sort to them // start customCollationOperation FindIterable cursor = collection.find() .collation(Collation.builder().locale("is").build()) diff --git a/source/includes/fundamentals/code-snippets/CompoundOperators.java b/source/includes/fundamentals/code-snippets/CompoundOperators.java index 154f70c10..08480b933 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -114,10 +114,10 @@ class DemoClientUnsafe extends DemoClient { // start the-unsafe-book-a-room public void bookARoom() { - // Creates a filter to match documents representing available rooms + // Creates a filter to match documents representing available rooms Bson filter = Filters.eq("reserved", false); - // Finds the first available room + // 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 diff --git a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java index bb39d68f2..ea78ebdcc 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java @@ -57,10 +57,10 @@ private void findOneAndUpdateExample() { //start findOneAndUpdate-example // - // Configures a projection to exclude the "_id" field from the printed documents + // Creates a projection to exclude the "_id" field from the printed documents Bson projection = Projections.excludeId(); - // Defines a filter to match documents with a "color" value of "green" + // 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" @@ -86,13 +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); - // Runs the operation and prints the deleted document + // 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 @@ -104,6 +106,7 @@ 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"); From ec3086288cc0b50c15b6dff8612aa438df33297b Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 18 Oct 2023 16:37:20 -0400 Subject: [PATCH 09/10] small edit --- source/includes/fundamentals/code-snippets/AggTour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/includes/fundamentals/code-snippets/AggTour.java b/source/includes/fundamentals/code-snippets/AggTour.java index f6aebd15e..00d663de9 100644 --- a/source/includes/fundamentals/code-snippets/AggTour.java +++ b/source/includes/fundamentals/code-snippets/AggTour.java @@ -55,7 +55,7 @@ public static void main(String[] args) { Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)) ) - // Prints the result of the aggregation pipeline as JSON + // Prints the result of the aggregation operation as JSON ).forEach(doc -> System.out.println(doc.toJson())); // end aggregation one From 68f46ec15f45f04359c0fe2374314c2a75e468c3 Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 27 Oct 2023 13:20:23 -0400 Subject: [PATCH 10/10] final feedback --- .../fundamentals/code-snippets/BulkWrite.java | 18 +++++++++--------- .../CollationCollectionExample.java | 6 +++--- .../code-snippets/CompoundOperators.java | 2 +- .../CompoundOperatorsIndividualExamples.java | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java index b6c047138..52f806b73 100644 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -88,7 +88,7 @@ private void insertExceptionExample() { // Runs a bulk write operation for the specified insert WriteModels collection.bulkWrite(bulkOperations); - // Prints a message if any exceptions occur during the operations + // Prints a message if any exceptions occur during the bulk write operation } catch (MongoBulkWriteException e){ System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); } @@ -103,7 +103,7 @@ private void bulkWriteNotOrderedExample() { .append("name", "Zaynab Omar") .append("age", 37)); - // Creates instructions to replace the matching document + // 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")); @@ -112,7 +112,7 @@ private void bulkWriteNotOrderedExample() { UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), Updates.set("name", "Zaynab Hassan")); - // Creates instructions to delete all matching documents + // Creates instructions to delete all documents that match the query DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -137,16 +137,16 @@ private void bulkWriteExample() { .append("name", "Zaynab Omar") .append("age", 37)); - // Creates instructions to replace the matching document + // 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")); - // Creates instructions to update the matching document + // 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 matching documents + // Creates instructions to delete all documents matched by the query DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); bulkOperations.add(insertDoc); @@ -181,7 +181,7 @@ private void insertDocumentsExample(){ private void replaceDocumentsExample(){ List> bulkOperations = new ArrayList<>(); - // Creates instructions to replace the matching document + // Creates instructions to replace the first document matched by the query // begin replaceDocumentsExample ReplaceOneModel celineDoc = new ReplaceOneModel<>( Filters.eq("_id", 1), @@ -198,7 +198,7 @@ private void replaceDocumentsExample(){ private void updateDocumentsExample(){ List> bulkOperations = new ArrayList<>(); - // Creates instructions to update the matching document + // Creates instructions to update the first document matched by the query // begin updateDocumentsExample UpdateOneModel updateDoc = new UpdateOneModel<>( Filters.eq("_id", 2), @@ -214,7 +214,7 @@ private void updateDocumentsExample(){ private void deleteDocumentsExample(){ List> bulkOperations = new ArrayList<>(); - // Creates instructions to delete the matching document + // Creates instructions to delete the first document matched by the query // begin deleteDocumentsExample DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); //end deleteDocumentsExample diff --git a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java index 9fae6d99a..2a41372b5 100644 --- a/source/includes/fundamentals/code-snippets/CollationCollectionExample.java +++ b/source/includes/fundamentals/code-snippets/CollationCollectionExample.java @@ -46,7 +46,7 @@ private static void aggregatesExample(MongoCollection collection) { // 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 results of the aggregation that tallied value frequencies and sorted the results + // Prints the JSON representation of the results if (results != null) { results.forEach(doc -> System.out.println(doc.toJson())); } @@ -80,7 +80,7 @@ private static void findOneAndUpdateExample(MongoCollection collection .sort(Sorts.ascending("first_name")) .returnDocument(ReturnDocument.AFTER)); - // Prints the JSON representation of the updated document, if an update occurred + // Prints the JSON representation of the updated document if an update occurred if (result != null) { System.out.println("Updated document: " + result.toJson()); } @@ -219,7 +219,7 @@ private static void customCollationOperation(MongoCollection collection) { } private static void operationCollation(MongoCollection collection) { - // Runs a find operation that meets the criteria for using the "name" field index + // 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()) diff --git a/source/includes/fundamentals/code-snippets/CompoundOperators.java b/source/includes/fundamentals/code-snippets/CompoundOperators.java index 08480b933..84b85c14a 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperators.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperators.java @@ -164,7 +164,7 @@ public void bookARoom(){ // Creates a filter to match a document representing an available room Bson filter = Filters.eq("reserved", false); - // Atomically finds and updates a document to mark it as reserved + // 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 diff --git a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java index ea78ebdcc..3102c5120 100644 --- a/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java +++ b/source/includes/fundamentals/code-snippets/CompoundOperatorsIndividualExamples.java @@ -57,7 +57,7 @@ private void findOneAndUpdateExample() { //start findOneAndUpdate-example // - // Creates a projection to exclude the "_id" field from the printed documents + // 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"