From 26dd0cadfe956ffd0087962c5a697cf5fcc8e828 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 19 Feb 2025 15:24:27 -0500 Subject: [PATCH 01/27] bulk write eg --- source/includes/crud/BulkWrite.java | 257 ++++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 source/includes/crud/BulkWrite.java diff --git a/source/includes/crud/BulkWrite.java b/source/includes/crud/BulkWrite.java new file mode 100644 index 000000000..52f806b73 --- /dev/null +++ b/source/includes/crud/BulkWrite.java @@ -0,0 +1,257 @@ +package docs; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.model.ReplaceOneModel; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.DeleteOneModel; +import com.mongodb.client.model.DeleteManyModel; + +import com.mongodb.MongoBulkWriteException; + +import org.bson.Document; + +import java.util.*; + +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import com.mongodb.client.model.WriteModel; + +public class BulkWrite { + + private final MongoCollection collection; + private final MongoClient mongoClient; + private final MongoDatabase database; + + private BulkWrite() { + final String uri = System.getenv("DRIVER_REF_URI"); + + mongoClient = MongoClients.create(uri); + database = mongoClient.getDatabase("crudOps"); + collection = database.getCollection("bulkWrite"); + } + + public static void main(String[] args) { + BulkWrite bulkWrite = new BulkWrite(); + System.out.println("Ordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteExample(); + bulkWrite.preview(); + + System.out.println("Unordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteNotOrderedExample(); + bulkWrite.preview(); + + System.out.println("Insert BulkWriteException"); + bulkWrite.setUpCollection(); + bulkWrite.insertExceptionExample(); + + System.out.println("Insert"); + bulkWrite.setUpCollection(); + bulkWrite.insertDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Replace"); + bulkWrite.setUpCollection(); + bulkWrite.replaceDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Update"); + bulkWrite.setUpCollection(); + bulkWrite.updateDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Delete"); + bulkWrite.setUpCollection(); + bulkWrite.deleteDocumentsExample(); + bulkWrite.preview(); + } + + + private void insertExceptionExample() { + // begin insertExceptionExample + try { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert documents + InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); + InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); + + bulkOperations.add(doc1); + bulkOperations.add(doc3); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + + // Prints a message if any exceptions occur during the bulk write operation + } catch (MongoBulkWriteException e){ + System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); + } + //end insertExceptionExample + } + + private void bulkWriteNotOrderedExample() { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // Creates instructions to replace the first document that matches the query + ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), + new Document("name", "Sandy Kane") + .append("location", "Helena, MT")); + + // Creates instructions to update the first document that matches the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents that match the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // begin bulkWriteNotOrderedExample + BulkWriteOptions options = new BulkWriteOptions().ordered(false); + + // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order + collection.bulkWrite(bulkOperations, options); + //end bulkWriteNotOrderedExample + } + + private void bulkWriteExample() { + // begin bulkWriteExample + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // 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 first document matched by the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents matched by the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order + collection.bulkWrite(bulkOperations); + //end bulkWriteExample + } + + private void insertDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert multiple documents + // begin insertDocumentsExample + InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") + .append("age", 17)); + + InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") + .append("age", 22)); + //end insertDocumentsExample + + bulkOperations.add(juneDoc); + bulkOperations.add(kevinDoc); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + } + + private void replaceDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to replace the first document matched by the query + // begin replaceDocumentsExample + ReplaceOneModel celineDoc = new ReplaceOneModel<>( + Filters.eq("_id", 1), + new Document("name", "Celine Stork") + .append("location", "San Diego, CA")); + //end replaceDocumentsExample + + bulkOperations.add(celineDoc); + + // Runs a bulk write operation for the specified replace WriteModel + collection.bulkWrite(bulkOperations); + } + + private void updateDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to update the first document matched by the query + // begin updateDocumentsExample + UpdateOneModel updateDoc = new UpdateOneModel<>( + Filters.eq("_id", 2), + Updates.set("age", 31)); + //end updateDocumentsExample + + bulkOperations.add(updateDoc); + + // Runs a bulk write operation for the specified update WriteModel + collection.bulkWrite(bulkOperations); + } + + private void deleteDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to delete the first document matched by the query + // begin deleteDocumentsExample + DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); + //end deleteDocumentsExample + + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified delete WriteModel + collection.bulkWrite(bulkOperations); + } + + private void preview(){ + collection.find().forEach(doc -> System.out.println(doc.toJson())); + } + + private void setUpCollection(){ + collection.drop(); + + //begin bulkOpsList + List> bulkOperations = new ArrayList<>(); + //end bulkOpsList + + InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) + .append("name", "Karen Sandoval") + .append("age", 31)); + + InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) + .append("name", "William Chin") + .append("age", 54)); + + InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) + .append("name", "Shayla Ray") + .append("age", 20)); + + bulkOperations.add(karen); + bulkOperations.add(william); + bulkOperations.add(shayla); + + collection.bulkWrite(bulkOperations); + } +} From eee10729bf4ed1b9fd3863b657a47586c2c3eee0 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 20 Feb 2025 11:41:47 -0500 Subject: [PATCH 02/27] update bulk write eg --- source/crud/bulk.txt | 27 ++ .../code-snippets/bulk-write/BulkWrite.java | 257 ------------------ source/usage-examples/bulkWrite.txt | 2 +- 3 files changed, 28 insertions(+), 258 deletions(-) delete mode 100644 source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index f08fcf22d..bad545bca 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -1,4 +1,5 @@ .. _java-fundamentals-bulkwrite: +.. _java-usage-bulkwrite: ===================== Bulk Write Operations @@ -358,6 +359,32 @@ see the following API documentation: - `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ + +Example File +~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs an ordered bulk +write operation on the ``movies`` collection in the ``sample_mflix`` database. +The example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, +``UpdateOneModel``, and ``DeleteOneModel``. + +.. include:: /includes/connect-guide-note.rst + +.. io-code-block:: + + .. input:: /includes/usage-examples/code-snippets/BulkWrite.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Result statistics: + inserted: 3 + updated: 2 + deleted: 1 + .. _java-sync-client-bulk-write: Client Bulk Write diff --git a/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java b/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java deleted file mode 100644 index 52f806b73..000000000 --- a/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java +++ /dev/null @@ -1,257 +0,0 @@ -package docs; - -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.InsertOneModel; -import com.mongodb.client.model.UpdateOneModel; -import com.mongodb.client.model.ReplaceOneModel; -import com.mongodb.client.model.BulkWriteOptions; -import com.mongodb.client.model.DeleteOneModel; -import com.mongodb.client.model.DeleteManyModel; - -import com.mongodb.MongoBulkWriteException; - -import org.bson.Document; - -import java.util.*; - -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import com.mongodb.client.model.WriteModel; - -public class BulkWrite { - - private final MongoCollection collection; - private final MongoClient mongoClient; - private final MongoDatabase database; - - private BulkWrite() { - final String uri = System.getenv("DRIVER_REF_URI"); - - mongoClient = MongoClients.create(uri); - database = mongoClient.getDatabase("crudOps"); - collection = database.getCollection("bulkWrite"); - } - - public static void main(String[] args) { - BulkWrite bulkWrite = new BulkWrite(); - System.out.println("Ordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteExample(); - bulkWrite.preview(); - - System.out.println("Unordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteNotOrderedExample(); - bulkWrite.preview(); - - System.out.println("Insert BulkWriteException"); - bulkWrite.setUpCollection(); - bulkWrite.insertExceptionExample(); - - System.out.println("Insert"); - bulkWrite.setUpCollection(); - bulkWrite.insertDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Replace"); - bulkWrite.setUpCollection(); - bulkWrite.replaceDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Update"); - bulkWrite.setUpCollection(); - bulkWrite.updateDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Delete"); - bulkWrite.setUpCollection(); - bulkWrite.deleteDocumentsExample(); - bulkWrite.preview(); - } - - - private void insertExceptionExample() { - // begin insertExceptionExample - try { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert documents - InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); - InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); - - bulkOperations.add(doc1); - bulkOperations.add(doc3); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - - // Prints a message if any exceptions occur during the bulk write operation - } catch (MongoBulkWriteException e){ - System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); - } - //end insertExceptionExample - } - - private void bulkWriteNotOrderedExample() { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // Creates instructions to replace the first document that matches the query - ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), - new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); - - // Creates instructions to update the first document that matches the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents that match the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // begin bulkWriteNotOrderedExample - BulkWriteOptions options = new BulkWriteOptions().ordered(false); - - // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order - collection.bulkWrite(bulkOperations, options); - //end bulkWriteNotOrderedExample - } - - private void bulkWriteExample() { - // begin bulkWriteExample - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // 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 first document matched by the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents matched by the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order - collection.bulkWrite(bulkOperations); - //end bulkWriteExample - } - - private void insertDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert multiple documents - // begin insertDocumentsExample - InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") - .append("age", 17)); - - InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") - .append("age", 22)); - //end insertDocumentsExample - - bulkOperations.add(juneDoc); - bulkOperations.add(kevinDoc); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - } - - private void replaceDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to replace the first document matched by the query - // begin replaceDocumentsExample - ReplaceOneModel celineDoc = new ReplaceOneModel<>( - Filters.eq("_id", 1), - new Document("name", "Celine Stork") - .append("location", "San Diego, CA")); - //end replaceDocumentsExample - - bulkOperations.add(celineDoc); - - // Runs a bulk write operation for the specified replace WriteModel - collection.bulkWrite(bulkOperations); - } - - private void updateDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to update the first document matched by the query - // begin updateDocumentsExample - UpdateOneModel updateDoc = new UpdateOneModel<>( - Filters.eq("_id", 2), - Updates.set("age", 31)); - //end updateDocumentsExample - - bulkOperations.add(updateDoc); - - // Runs a bulk write operation for the specified update WriteModel - collection.bulkWrite(bulkOperations); - } - - private void deleteDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to delete the first document matched by the query - // begin deleteDocumentsExample - DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); - //end deleteDocumentsExample - - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified delete WriteModel - collection.bulkWrite(bulkOperations); - } - - private void preview(){ - collection.find().forEach(doc -> System.out.println(doc.toJson())); - } - - private void setUpCollection(){ - collection.drop(); - - //begin bulkOpsList - List> bulkOperations = new ArrayList<>(); - //end bulkOpsList - - InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) - .append("name", "Karen Sandoval") - .append("age", 31)); - - InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) - .append("name", "William Chin") - .append("age", 54)); - - InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) - .append("name", "Shayla Ray") - .append("age", 20)); - - bulkOperations.add(karen); - bulkOperations.add(william); - bulkOperations.add(shayla); - - collection.bulkWrite(bulkOperations); - } -} diff --git a/source/usage-examples/bulkWrite.txt b/source/usage-examples/bulkWrite.txt index c083a7c10..67205f1ae 100644 --- a/source/usage-examples/bulkWrite.txt +++ b/source/usage-examples/bulkWrite.txt @@ -1,4 +1,4 @@ -.. _java-usage-bulkwrite: + ======================= Perform Bulk Operations From 4239ea0a6106073eac43216118dd3ff7f0c3b990 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 21 Feb 2025 10:29:18 -0500 Subject: [PATCH 03/27] add data details --- source/crud/bulk.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index bad545bca..7d012e3b7 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -364,7 +364,11 @@ Example File ~~~~~~~~~~~~ The following code is a complete, standalone file that performs an ordered bulk -write operation on the ``movies`` collection in the ``sample_mflix`` database. +write operation. + +.. include:: /includes/sample-data-note.rst + +It uses the on the ``movies`` collection in the ``sample_mflix`` database. The example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, ``UpdateOneModel``, and ``DeleteOneModel``. From 1f6b8655563f62cc56cbba3ae9a502da83f803d8 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 21 Feb 2025 10:29:53 -0500 Subject: [PATCH 04/27] add data details --- source/crud/bulk.txt | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 7d012e3b7..a3bd11491 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -363,15 +363,21 @@ see the following API documentation: Example File ~~~~~~~~~~~~ -The following code is a complete, standalone file that performs an ordered bulk -write operation. +This code example is a complete, standalone file that performs an ordered bulk +write operation. It uses the on the ``movies`` collection in the +``sample_mflix`` database included in the :atlas:`sample datasets +` provided by Atlas. You can load them into +your database on the free tier of MongoDB Atlas by following the :atlas:`Get +Started with Atlas Guide ` .. include:: /includes/sample-data-note.rst -It uses the on the ``movies`` collection in the ``sample_mflix`` database. + The example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, ``UpdateOneModel``, and ``DeleteOneModel``. +The following code + .. include:: /includes/connect-guide-note.rst .. io-code-block:: From 80d972367e182ee45cd5c2143aff39beee822ae2 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 21 Feb 2025 13:35:17 -0500 Subject: [PATCH 05/27] intro --- source/crud/bulk.txt | 11 +- source/includes/crud/BulkWrite.java | 292 +++--------------- .../code-snippets/BulkWrite.java | 59 ---- 3 files changed, 51 insertions(+), 311 deletions(-) delete mode 100644 source/includes/usage-examples/code-snippets/BulkWrite.java diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index a3bd11491..773804494 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -360,8 +360,8 @@ see the following API documentation: - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ -Example File -~~~~~~~~~~~~ +BulkWrite Example File +~~~~~~~~~~~~~~~~~~~~~~ This code example is a complete, standalone file that performs an ordered bulk write operation. It uses the on the ``movies`` collection in the @@ -372,11 +372,8 @@ Started with Atlas Guide collection; - private final MongoClient mongoClient; - private final MongoDatabase database; - - private BulkWrite() { - final String uri = System.getenv("DRIVER_REF_URI"); - - mongoClient = MongoClients.create(uri); - database = mongoClient.getDatabase("crudOps"); - collection = database.getCollection("bulkWrite"); - } - public static void main(String[] args) { - BulkWrite bulkWrite = new BulkWrite(); - System.out.println("Ordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteExample(); - bulkWrite.preview(); - - System.out.println("Unordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteNotOrderedExample(); - bulkWrite.preview(); - - System.out.println("Insert BulkWriteException"); - bulkWrite.setUpCollection(); - bulkWrite.insertExceptionExample(); - - System.out.println("Insert"); - bulkWrite.setUpCollection(); - bulkWrite.insertDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Replace"); - bulkWrite.setUpCollection(); - bulkWrite.replaceDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Update"); - bulkWrite.setUpCollection(); - bulkWrite.updateDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Delete"); - bulkWrite.setUpCollection(); - bulkWrite.deleteDocumentsExample(); - bulkWrite.preview(); - } - - - private void insertExceptionExample() { - // begin insertExceptionExample - try { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert documents - InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); - InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); - - bulkOperations.add(doc1); - bulkOperations.add(doc3); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - - // Prints a message if any exceptions occur during the bulk write operation - } catch (MongoBulkWriteException e){ - System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); + // Replace the uri string with your MongoDB deployment's connection string + String uri = ""; + + try (MongoClient mongoClient = MongoClients.create(uri)) { + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); + MongoCollection collection = database.getCollection("movies"); + + try { + // Runs a bulk write operation for the specified insert, update, delete, and replace operations + BulkWriteResult result = collection.bulkWrite( + Arrays.asList( + new InsertOneModel<>(new Document("name", "A Sample Movie")), + new InsertOneModel<>(new Document("name", "Another Sample Movie")), + new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new UpdateOneModel<>(new Document("name", "A Sample Movie"), + new Document("$set", new Document("name", "An Old Sample Movie")), + new UpdateOptions().upsert(true)), + + new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), + new Document("name", "The Other Sample Movie").append("runtime", "42")) + )); + // Prints the number of inserted, updated, and deleted documents + System.out.println("Result statistics:" + + "\ninserted: " + result.getInsertedCount() + + "\nupdated: " + result.getModifiedCount() + + "\ndeleted: " + result.getDeletedCount()); + + // Prints a message if any exceptions occur during the operations + } catch (MongoException me) { + System.err.println("The bulk write operation failed due to an error: " + me); + } } - //end insertExceptionExample - } - - private void bulkWriteNotOrderedExample() { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // Creates instructions to replace the first document that matches the query - ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), - new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); - - // Creates instructions to update the first document that matches the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents that match the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // begin bulkWriteNotOrderedExample - BulkWriteOptions options = new BulkWriteOptions().ordered(false); - - // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order - collection.bulkWrite(bulkOperations, options); - //end bulkWriteNotOrderedExample - } - - private void bulkWriteExample() { - // begin bulkWriteExample - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // 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 first document matched by the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents matched by the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order - collection.bulkWrite(bulkOperations); - //end bulkWriteExample - } - - private void insertDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert multiple documents - // begin insertDocumentsExample - InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") - .append("age", 17)); - - InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") - .append("age", 22)); - //end insertDocumentsExample - - bulkOperations.add(juneDoc); - bulkOperations.add(kevinDoc); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - } - - private void replaceDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to replace the first document matched by the query - // begin replaceDocumentsExample - ReplaceOneModel celineDoc = new ReplaceOneModel<>( - Filters.eq("_id", 1), - new Document("name", "Celine Stork") - .append("location", "San Diego, CA")); - //end replaceDocumentsExample - - bulkOperations.add(celineDoc); - - // Runs a bulk write operation for the specified replace WriteModel - collection.bulkWrite(bulkOperations); - } - - private void updateDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to update the first document matched by the query - // begin updateDocumentsExample - UpdateOneModel updateDoc = new UpdateOneModel<>( - Filters.eq("_id", 2), - Updates.set("age", 31)); - //end updateDocumentsExample - - bulkOperations.add(updateDoc); - - // Runs a bulk write operation for the specified update WriteModel - collection.bulkWrite(bulkOperations); - } - - private void deleteDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to delete the first document matched by the query - // begin deleteDocumentsExample - DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); - //end deleteDocumentsExample - - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified delete WriteModel - collection.bulkWrite(bulkOperations); - } - - private void preview(){ - collection.find().forEach(doc -> System.out.println(doc.toJson())); - } - - private void setUpCollection(){ - collection.drop(); - - //begin bulkOpsList - List> bulkOperations = new ArrayList<>(); - //end bulkOpsList - - InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) - .append("name", "Karen Sandoval") - .append("age", 31)); - - InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) - .append("name", "William Chin") - .append("age", 54)); - - InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) - .append("name", "Shayla Ray") - .append("age", 20)); - - bulkOperations.add(karen); - bulkOperations.add(william); - bulkOperations.add(shayla); - - collection.bulkWrite(bulkOperations); } -} +} \ No newline at end of file diff --git a/source/includes/usage-examples/code-snippets/BulkWrite.java b/source/includes/usage-examples/code-snippets/BulkWrite.java deleted file mode 100644 index d8cfd4452..000000000 --- a/source/includes/usage-examples/code-snippets/BulkWrite.java +++ /dev/null @@ -1,59 +0,0 @@ -// Runs bulk write operations on a collection by using the Java driver - -package usage.examples; - -import java.util.Arrays; - -import org.bson.Document; - -import com.mongodb.MongoException; -import com.mongodb.bulk.BulkWriteResult; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.DeleteOneModel; -import com.mongodb.client.model.InsertOneModel; -import com.mongodb.client.model.ReplaceOneModel; -import com.mongodb.client.model.UpdateOneModel; -import com.mongodb.client.model.UpdateOptions; - -public class BulkWrite { - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - try { - // Runs a bulk write operation for the specified insert, update, delete, and replace operations - BulkWriteResult result = collection.bulkWrite( - Arrays.asList( - new InsertOneModel<>(new Document("name", "A Sample Movie")), - new InsertOneModel<>(new Document("name", "Another Sample Movie")), - new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new UpdateOneModel<>(new Document("name", "A Sample Movie"), - new Document("$set", new Document("name", "An Old Sample Movie")), - new UpdateOptions().upsert(true)), - - new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), - new Document("name", "The Other Sample Movie").append("runtime", "42")) - )); - // Prints the number of inserted, updated, and deleted documents - System.out.println("Result statistics:" + - "\ninserted: " + result.getInsertedCount() + - "\nupdated: " + result.getModifiedCount() + - "\ndeleted: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operations - } catch (MongoException me) { - System.err.println("The bulk write operation failed due to an error: " + me); - } - } - } -} \ No newline at end of file From 6c0eca9c39c69056b1742915e57858e819660e07 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 21 Feb 2025 14:00:36 -0500 Subject: [PATCH 06/27] delete --- source/crud/bulk.txt | 6 +- source/crud/delete.txt | 57 +++++++-- .../DeleteOne.java => crud/Delete.java} | 20 ++- .../code-snippets/DeleteMany.java | 42 ------- source/usage-examples/bulkWrite.txt | 115 ------------------ 5 files changed, 68 insertions(+), 172 deletions(-) rename source/includes/{usage-examples/code-snippets/DeleteOne.java => crud/Delete.java} (60%) delete mode 100644 source/includes/usage-examples/code-snippets/DeleteMany.java delete mode 100644 source/usage-examples/bulkWrite.txt diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 773804494..1877f763d 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -364,14 +364,12 @@ BulkWrite Example File ~~~~~~~~~~~~~~~~~~~~~~ This code example is a complete, standalone file that performs an ordered bulk -write operation. It uses the on the ``movies`` collection in the +write operation. It uses the ``movies`` collection in the ``sample_mflix`` database included in the :atlas:`sample datasets ` provided by Atlas. You can load them into your database on the free tier of MongoDB Atlas by following the :atlas:`Get Started with Atlas Guide ` -.. include:: /includes/sample-data-note.rst - This example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, ``UpdateOneModel``, ``DeleteOneModel``, and ``ReplaceOneModel``. @@ -379,7 +377,7 @@ This example call to ``bulkWrite()`` includes examples of the ``InsertOneModel`` .. io-code-block:: - .. input:: /includes/usage-examples/code-snippets/BulkWrite.java + .. input:: /includes/crud/BulkWrite.java :language: java :dedent: diff --git a/source/crud/delete.txt b/source/crud/delete.txt index d4d70e883..3a004c9a0 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -1,4 +1,5 @@ .. _java-fundamentals-delete: +.. _java-usage-deletemany: ================ Delete Documents @@ -147,14 +148,54 @@ collection: { "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 } +Delete Example File +------------------- + +This code example is a complete, standalone file that performs a delete one +operation and a delete many operation. It uses the ``movies`` collection in the +``sample_mflix`` database included in the :atlas:`sample datasets +` provided by Atlas. You can load them into +your database on the free tier of MongoDB Atlas by following the :atlas:`Get +Started with Atlas Guide ` + +This example used the ``eq()`` and ``lt()`` filters to query documents. For more +information about filters, see the `Filters Class +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ +API documentation. + +.. include:: /includes/connect-guide-note.rst + +.. io-code-block:: + + .. input:: /includes/crud/Delete.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + DeleteOne document count: 1 + DeleteMany document count: 4 + +More Information +---------------- + For more information about the methods and classes mentioned in this guide, see the following resources: -- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ API Documentation -- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ API Documentation -- `findOneAndDelete() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndDelete(org.bson.conversions.Bson)>`__ API Documentation -- `DeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOptions.html>`__ API Documentation -- `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ API Documentation -- :manual:`db.collection.deleteOne() ` Server Manual Entry -- :manual:`db.collection.deleteMany() ` Server Manual Entry -- :manual:`db.collection.findOneAndDelete() ` Server Manual Entry +API Documentation +~~~~~~~~~~~~~~~~~ + +- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ +- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ +- `findOneAndDelete() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndDelete(org.bson.conversions.Bson)>`__ +- `DeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOptions.html>`__ +- `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ + +- :manual:`db.collection.deleteOne() ` +- :manual:`db.collection.deleteMany() ` +- :manual:`db.collection.findOneAndDelete() ` diff --git a/source/includes/usage-examples/code-snippets/DeleteOne.java b/source/includes/crud/Delete.java similarity index 60% rename from source/includes/usage-examples/code-snippets/DeleteOne.java rename to source/includes/crud/Delete.java index 4ff02f20b..4ae54a742 100644 --- a/source/includes/usage-examples/code-snippets/DeleteOne.java +++ b/source/includes/crud/Delete.java @@ -25,17 +25,31 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - Bson query = eq("title", "The Garbage Pail Kids Movie"); + Bson deleteOneQuery = eq("title", "The Garbage Pail Kids Movie"); try { // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" - DeleteResult result = collection.deleteOne(query); - System.out.println("Deleted document count: " + result.getDeletedCount()); + DeleteResult deleteOneResult = collection.deleteOne(deleteOneQuery); + System.out.println("Deleted document count: " + deleteOneResult.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { System.err.println("Unable to delete due to an error: " + me); } + + Bson deleteManyQuery = lt("imdb.rating", 1.9); + + try { + // Deletes all documents that have an "imdb.rating" value less than 1.9 + DeleteResult deleteManyResult = collection.deleteMany(deleteManyQuery); + + // Prints the number of deleted documents + System.out.println("Deleted document count: " + deleteManyResult.getDeletedCount()); + + // Prints a message if any exceptions occur during the operation + } catch (MongoException me) { + System.err.println("Unable to delete due to an error: " + me); + } } } } \ No newline at end of file diff --git a/source/includes/usage-examples/code-snippets/DeleteMany.java b/source/includes/usage-examples/code-snippets/DeleteMany.java deleted file mode 100644 index 2eccff1e6..000000000 --- a/source/includes/usage-examples/code-snippets/DeleteMany.java +++ /dev/null @@ -1,42 +0,0 @@ -// Deletes multiple documents from a collection by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.lt; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.result.DeleteResult; - -public class DeleteMany { - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Bson query = lt("imdb.rating", 1.9); - - try { - // Deletes all documents that have an "imdb.rating" value less than 1.9 - DeleteResult result = collection.deleteMany(query); - - // Prints the number of deleted documents - System.out.println("Deleted document count: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to delete due to an error: " + me); - } - } - } -} \ No newline at end of file diff --git a/source/usage-examples/bulkWrite.txt b/source/usage-examples/bulkWrite.txt deleted file mode 100644 index 67205f1ae..000000000 --- a/source/usage-examples/bulkWrite.txt +++ /dev/null @@ -1,115 +0,0 @@ - - -======================= -Perform Bulk Operations -======================= - - - - -The ``bulkWrite()`` method performs batch write operations against a -*single* collection. This method reduces the number of network round trips from -your application to your MongoDB instance which increases the performance of your -application. Since you only receive the success status after -all the operations return, we recommend you use this if that meets the -requirements of your use case. - -You can specify one or more of the following write operations in -``bulkWrite()``: - -- Insert a document -- Update a document -- Update multiple documents -- Delete a document -- Delete multiple documents -- Replace a document - -The ``bulkWrite()`` method accepts the following parameters: - -- A ``List`` of objects that implement ``WriteModel``: the classes that - implement ``WriteModel`` correspond to the preceding write - operations. For example, the ``InsertOneModel`` class wraps the - ``insertOne()`` write method, which inserts a document. See the links - to the API documentation at the end of this page for more information - about each class. - -- ``BulkWriteOptions``: *optional* object that specifies settings such as - whether to ensure your MongoDB instance orders your write operations. - -.. note:: - - Retryable writes run on {+mdb-server+} versions 3.6 or later in bulk - write operations unless they include one or more instances of - ``UpdateManyModel`` or ``DeleteManyModel``. - -.. tip:: - - By default, MongoDB executes operations in a bulk write in the - specified order. During an ordered bulk write, if - an error occurs during the processing of an operation, MongoDB returns - without processing the remaining operations in the list. - - In contrast, when you set the ``ordered`` option to ``false``, MongoDB - continues to process the remaining write operations in the list even in the - event of an error. Unordered operations are usually faster since - MongoDB can execute them in parallel, but only use an - unordered bulk write if the order of your write operations is not - important. - -The ``bulkWrite()`` method returns a ``BulkWriteResult`` object that -contains information about the write operation results including the number -of documents inserted, modified, and deleted. - -If one or more of your operations attempts to set a value that violates a -unique index on your collection, an exception is raised that should look -something like this: - -.. code-block:: sh - :copyable: false - - The bulk write operation failed due to an error: Bulk write operation error on server . Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: ... }]. - -Similarly, if you attempt to perform a bulk write against a collection -that uses schema validation and one or more of your write operations -provide an unexpected format, you might encounter exceptions. - -Example -------- - -The following code sample performs an ordered bulk write operation on the -``movies`` collection in the ``sample_mflix`` database. The example call -to ``bulkWrite()`` includes examples of the ``InsertOneModel``, -``UpdateOneModel``, and ``DeleteOneModel``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/BulkWrite.java - :language: java - -The output of the preceding code resembles the following: - -.. code-block:: none - :copyable: false - - Result statistics: - inserted: 3 - updated: 2 - deleted: 1 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following resources: - -- :manual:`Unique Index ` Server Manual Entry -- :manual:`Schema Validation ` Server Manual Entry -- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#bulkWrite(java.util.List,com.mongodb.client.model.BulkWriteOptions)>`__ API Documentation -- `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ API Documentation -- `BulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/bulk/BulkWriteResult.html>`__ API Documentation -- `InsertOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/InsertOneModel.html>`__ API Documentation -- `UpdateOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOneModel.html>`__ API Documentation -- `UpdateManyModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateManyModel.html>`__ API Documentation -- `DeleteOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOneModel.html>`__ API Documentation -- `DeleteManyModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteManyModel.html>`__ API Documentation -- `ReplaceOneModel <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOneModel.html>`__ API Documentation - From f7757d2d505e4129e840383bfd153cf33c07af00 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 21 Feb 2025 15:43:10 -0500 Subject: [PATCH 07/27] insert --- source/crud/bulk.txt | 16 ++--- source/crud/delete.txt | 18 +++--- source/crud/insert.txt | 43 ++++++++----- source/includes/crud/Delete.java | 4 +- .../InsertOne.java => crud/Insert.java} | 22 ++++++- source/includes/crud/example-intro.rst | 2 +- source/usage-examples/delete-operations.txt | 15 ----- source/usage-examples/deleteMany.txt | 58 ------------------ source/usage-examples/deleteOne.txt | 60 ------------------- 9 files changed, 63 insertions(+), 175 deletions(-) rename source/includes/{usage-examples/code-snippets/InsertOne.java => crud/Insert.java} (58%) delete mode 100644 source/usage-examples/delete-operations.txt delete mode 100644 source/usage-examples/deleteMany.txt delete mode 100644 source/usage-examples/deleteOne.txt diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 1877f763d..90ca9ca80 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -360,21 +360,17 @@ see the following API documentation: - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ -BulkWrite Example File -~~~~~~~~~~~~~~~~~~~~~~ +BulkWrite Example +~~~~~~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs an ordered bulk +write operation. -This code example is a complete, standalone file that performs an ordered bulk -write operation. It uses the ``movies`` collection in the -``sample_mflix`` database included in the :atlas:`sample datasets -` provided by Atlas. You can load them into -your database on the free tier of MongoDB Atlas by following the :atlas:`Get -Started with Atlas Guide ` +.. include:: /includes/crud/example-intro.rst This example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, ``UpdateOneModel``, ``DeleteOneModel``, and ``ReplaceOneModel``. -.. include:: /includes/connect-guide-note.rst - .. io-code-block:: .. input:: /includes/crud/BulkWrite.java diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 3a004c9a0..818ab5701 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -148,23 +148,19 @@ collection: { "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 } -Delete Example File -------------------- +Delete Example +-------------- -This code example is a complete, standalone file that performs a delete one -operation and a delete many operation. It uses the ``movies`` collection in the -``sample_mflix`` database included in the :atlas:`sample datasets -` provided by Atlas. You can load them into -your database on the free tier of MongoDB Atlas by following the :atlas:`Get -Started with Atlas Guide ` +The following code is a complete, standalone file that performs a delete one +operation and a delete many operation. -This example used the ``eq()`` and ``lt()`` filters to query documents. For more +.. include:: /includes/crud/example-intro.rst + +The query uses the ``eq()`` and ``lt()`` filters to query documents. For more information about filters, see the `Filters Class <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ API documentation. -.. include:: /includes/connect-guide-note.rst - .. io-code-block:: .. input:: /includes/crud/Delete.java diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 49fa6f734..3303c8196 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -159,26 +159,37 @@ The output of the preceding code resembles the following: .. code-block:: :copyable: false - Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8] + Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, + 60930c3aa982931c20ef6cd8] -For more information about the methods and classes mentioned in this section, -see the following resources: -- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ API Documentation -- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ API Documentation -- Manual Explanation on :manual:`insertMany() ` -- Runnable :ref:`Insert Multiple Documents Example ` +Insert Example +-------------- + +The following code is a complete, standalone file that performs an insert one +operation and an insert many operation. + +.. include:: /includes/crud/example-intro.rst + +.. io-code-block:: -Summary -------- + .. input:: /includes/crud/Insert.java + :language: java + :dedent: -There are three ways to perform an insert operation, but we focused on two: + .. output:: + :language: none + :visible: false -- The ``insertOne()`` method inserts a single document. -- The ``insertMany()`` method inserts multiple documents. + InsertOne document id: BsonObjectId{value=...} + InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} -Both methods automatically generate an ``_id`` if you omit the field in -your document. +More Information +---------------- + +For more information about the methods and classes mentioned in this section, +see the following resources: -If the insertion is successful, both methods return an instance -representing the ``_id`` of each new document. +- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ API Documentation +- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ API Documentation +- Manual Explanation on :manual:`insertMany() ` diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index 4ae54a742..c0199066c 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -30,7 +30,7 @@ public static void main(String[] args) { try { // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" DeleteResult deleteOneResult = collection.deleteOne(deleteOneQuery); - System.out.println("Deleted document count: " + deleteOneResult.getDeletedCount()); + System.out.println("DeleteOne document count: " + deleteOneResult.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { @@ -44,7 +44,7 @@ public static void main(String[] args) { DeleteResult deleteManyResult = collection.deleteMany(deleteManyQuery); // Prints the number of deleted documents - System.out.println("Deleted document count: " + deleteManyResult.getDeletedCount()); + System.out.println("DeleteMany document count: " + deleteManyResult.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { diff --git a/source/includes/usage-examples/code-snippets/InsertOne.java b/source/includes/crud/Insert.java similarity index 58% rename from source/includes/usage-examples/code-snippets/InsertOne.java rename to source/includes/crud/Insert.java index 0949ea5ab..fc45293e6 100644 --- a/source/includes/usage-examples/code-snippets/InsertOne.java +++ b/source/includes/crud/Insert.java @@ -13,6 +13,7 @@ import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.InsertOneResult; +import com.mongodb.client.result.InsertManyResult; public class InsertOne { public static void main(String[] args) { @@ -25,13 +26,30 @@ public static void main(String[] args) { try { // Inserts a sample document describing a movie into the collection - InsertOneResult result = collection.insertOne(new Document() + InsertOneResult iOResult = collection.insertOne(new Document() .append("_id", new ObjectId()) .append("title", "Ski Bloopers") .append("genres", Arrays.asList("Documentary", "Comedy"))); // Prints the ID of the inserted document - System.out.println("Success! Inserted document id: " + result.getInsertedId()); + System.out.println("InsertOne document id: " + result.getInsertedId()); + + // Prints a message if any exceptions occur during the operation + } catch (MongoException me) { + System.err.println("Unable to insert due to an error: " + me); + } + + // Creates two sample documents containing a "title" field + List movieList = Arrays.asList( + new Document().append("title", "Short Circuit 3"), + new Document().append("title", "The Lego Frozen Movie")); + + try { + // Inserts sample documents describing movies into the collection + InsertManyResult result = collection.insertMany(movieList); + + // Prints the IDs of the inserted documents + System.out.println("InsertMany document ids: " + result.getInsertedIds()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { diff --git a/source/includes/crud/example-intro.rst b/source/includes/crud/example-intro.rst index e2b1374dd..653f8277b 100644 --- a/source/includes/crud/example-intro.rst +++ b/source/includes/crud/example-intro.rst @@ -7,4 +7,4 @@ `. You can load them into your database on the free tier of MongoDB Atlas by following the :atlas:`Get Started with Atlas Guide - `. \ No newline at end of file + `. diff --git a/source/usage-examples/delete-operations.txt b/source/usage-examples/delete-operations.txt deleted file mode 100644 index 811d30db6..000000000 --- a/source/usage-examples/delete-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -================= -Delete Operations -================= - -.. meta:: - :description: Learn by example: how to delete data from MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Delete One - Delete Many - -- :doc:`Delete a Document ` -- :doc:`Delete Multiple Documents ` diff --git a/source/usage-examples/deleteMany.txt b/source/usage-examples/deleteMany.txt deleted file mode 100644 index 7fc4bbf7c..000000000 --- a/source/usage-examples/deleteMany.txt +++ /dev/null @@ -1,58 +0,0 @@ -.. _java-usage-deletemany: - -========================= -Delete Multiple Documents -========================= - - - -You can delete multiple documents from a collection in a single operation -by calling the ``deleteMany()`` method on a ``MongoCollection`` object. - -To specify which documents to delete, pass a query filter that matches -the documents you want to delete. If you provide an empty document, -MongoDB matches all documents in the collection and deletes them. While -you can use ``deleteMany()`` to delete all documents in a collection, -consider using the ``drop()`` method instead for better performance. - -Upon successful deletion, this method returns an instance of -``DeleteResult``. You can retrieve information such as the number of -documents deleted by calling the ``getDeletedCount()`` method on the -``DeleteResult`` instance. - -If your delete operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``deleteMany()``, linked at the bottom of -this page. - -Example -------- - -The following snippet deletes multiple documents from the ``movies`` -collection in the ``sample_mflix`` database. - -The query filter passed to the ``deleteMany()`` method matches all -movie documents that contain a ``rating`` of less than **1.9** in the ``imdb`` -subdocument. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/DeleteMany.java - :language: java - -When you run the example, you should see output that reports the number of -documents deleted in your call to ``deleteMany()``. - -.. code-block:: none - :copyable: false - - Deleted document count: 4 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ -- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ -- `drop() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#drop()>`__ diff --git a/source/usage-examples/deleteOne.txt b/source/usage-examples/deleteOne.txt deleted file mode 100644 index ff2557481..000000000 --- a/source/usage-examples/deleteOne.txt +++ /dev/null @@ -1,60 +0,0 @@ -.. _java-usage-deleteone: - -================= -Delete a Document -================= - - - -You can delete a single document from a collection using the ``deleteOne()`` -method on a ``MongoCollection`` object. The method accepts a query filter -that matches the document you want to delete. If you do not specify -a filter, MongoDB matches the first document in the collection. The -``deleteOne()`` method only deletes the first document matched. - -This method returns an instance of ``DeleteResult`` which contains information -including how many documents were deleted as a result of the operation. - -If your delete operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``deleteOne()``, linked at the bottom of -this page. - -Example -------- - -The following snippet deletes a single document from the ``movies`` -collection of the ``sample_mflix`` database. The example uses the ``eq()`` -filter to match movies with the ``title`` exactly matching the text -``'The Garbage Pail Kids Movie'``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/DeleteOne.java - :language: java - -When you run the example, if the query filter you passed in your call to -``deleteOne()`` matches a document and removes it, you should see output -that looks something like this: - -.. code-block:: none - :copyable: false - - Deleted document count: 1 - -If your query filter does not match a document in your collection, -your call to ``deleteOne()`` removes no documents and returns the following: - -.. code-block:: none - :copyable: false - - Deleted document count: 0 - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ -- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ -- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ From 27e13e74e35cf13cf359860f6dbf8893a9dddcb1 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Mon, 24 Feb 2025 08:05:16 -0500 Subject: [PATCH 08/27] modify --- source/crud/update-documents.txt | 117 +++++++++++++++++- source/includes/crud/Delete.java | 8 +- source/includes/crud/Insert.java | 2 +- .../UpdateOne.java => crud/Update.java} | 32 ++++- 4 files changed, 147 insertions(+), 12 deletions(-) rename source/includes/{usage-examples/code-snippets/UpdateOne.java => crud/Update.java} (63%) diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 79441a230..39ae4936c 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -170,4 +170,119 @@ documents match. to a document that violate unique index constraints on the collection. For more information about constraints on unique indexes, see :manual:`Unique Indexes ` in the - {+mdb-server+} manual. \ No newline at end of file + {+mdb-server+} manual. + +Update Example +~~~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs an update one +operation and an update many operation. + +.. include:: /includes/crud/example-intro.rst + +.. io-code-block:: + + .. input:: /includes/crud/Insert.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + InsertOne document id: BsonObjectId{value=...} + InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} + +.. _replace-operation: + +Replace +------- + +A replace operation substitutes one document from your collection. The +substitution occurs between a document your query filter matches and a +replacement document. + +The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ +method removes all the existing fields and values in the +matching document (except the ``_id`` field) and substitutes it with the +replacement document. + +You can call the ``replaceOne()`` method on a ``MongoCollection`` +instance as follows: + +.. code-block:: java + + collection.replaceOne(, ); + +Replace Operation Parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``replaceOne()`` method has the following parameters: + +- ``query`` specifies a query filter with the criteria to match a + document to replace in your collection. +- ``replacement`` specifies fields and values of a new ``Document`` + object to replace the matched document. +- *(Optional)* ``replaceOptions`` specifies options that you can set to + customize how the driver performs the replace operation. To learn more + about this type, see the API documentation for `ReplaceOptions + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__. + +Replace One Example +~~~~~~~~~~~~~~~~~~~ + +The paint store realizes they must update their inventory again. What they +thought was 20 cans of pink paint is actually 25 cans of orange paint. + +To update the inventory, call the ``replaceOne()`` method specifying the +following: + +- A query filter that matches documents where the ``color`` is "pink" +- A replacement document where the ``color`` is "orange" and the ``qty`` is "25" + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceOneExample + :end-before: end replaceOneExample + +The output of the preceding code resembles the following: + +.. code-block:: none + :copyable: false + + Matched document count: 1 + Modified document count: 1 + +The following shows the updated document: + +.. code-block:: json + :copyable: false + + { "_id": 5, "color": "orange", "qty": 25 } + +If multiple documents match the query filter specified in +the ``replaceOne()`` method, it replaces the first result. You can +specify a sort in a ``ReplaceOptions`` instance to apply an order to +matched documents before the server performs the replace operation, as +shown in the following code: + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceoptions + :end-before: end replaceoptions + +If zero documents match the query filter in the replace operation, +``replaceOne()`` makes no changes to documents in the collection. See +our :ref:`upsert guide ` to +learn how to insert a new document instead of replacing one if no +documents match. + +.. important:: + + The ``replaceOne()`` method cannot make changes to a document that + violate unique index constraints on the collection. + For more information about constraints on unique indexes, + see :manual:`Unique Indexes ` in the + {+mdb-server+} manual. diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index c0199066c..508d118a9 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -29,8 +29,8 @@ public static void main(String[] args) { try { // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" - DeleteResult deleteOneResult = collection.deleteOne(deleteOneQuery); - System.out.println("DeleteOne document count: " + deleteOneResult.getDeletedCount()); + DeleteResult result = collection.deleteOne(deleteOneQuery); + System.out.println("DeleteOne document count: " + result.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { @@ -41,10 +41,10 @@ public static void main(String[] args) { try { // Deletes all documents that have an "imdb.rating" value less than 1.9 - DeleteResult deleteManyResult = collection.deleteMany(deleteManyQuery); + DeleteResult result = collection.deleteMany(deleteManyQuery); // Prints the number of deleted documents - System.out.println("DeleteMany document count: " + deleteManyResult.getDeletedCount()); + System.out.println("DeleteMany document count: " + result.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index fc45293e6..f8a402648 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -26,7 +26,7 @@ public static void main(String[] args) { try { // Inserts a sample document describing a movie into the collection - InsertOneResult iOResult = collection.insertOne(new Document() + InsertOneResult result = collection.insertOne(new Document() .append("_id", new ObjectId()) .append("title", "Ski Bloopers") .append("genres", Arrays.asList("Documentary", "Comedy"))); diff --git a/source/includes/usage-examples/code-snippets/UpdateOne.java b/source/includes/crud/Update.java similarity index 63% rename from source/includes/usage-examples/code-snippets/UpdateOne.java rename to source/includes/crud/Update.java index 2bde4c1fc..5f08c7f1e 100644 --- a/source/includes/usage-examples/code-snippets/UpdateOne.java +++ b/source/includes/crud/Update.java @@ -24,20 +24,21 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - Document query = new Document().append("title", "Cool Runnings 2"); + // Instructs the driver to insert a new document if none match the query + UpdateOptions options = new UpdateOptions().upsert(true); + + + Document updateOneQuery = new Document().append("title", "Cool Runnings 2"); // Creates instructions to update the values of three document fields - Bson updates = Updates.combine( + Bson updateOneUpdates = Updates.combine( Updates.set("runtime", 99), Updates.addToSet("genres", "Sports"), Updates.currentTimestamp("lastUpdated")); - // Instructs the driver to insert a new document if none match the query - UpdateOptions options = new UpdateOptions().upsert(true); - try { // Updates the first document that has a "title" value of "Cool Runnings 2" - UpdateResult result = collection.updateOne(query, updates, options); + UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed System.out.println("Modified document count: " + result.getModifiedCount()); @@ -47,6 +48,25 @@ public static void main(String[] args) { } catch (MongoException me) { System.err.println("Unable to update due to an error: " + me); } + + Bson updateManyQuery = gt("num_mflix_comments", 50); + + // Creates instructions to update the values of two document fields + Bson updateManyUpdates = Updates.combine( + Updates.addToSet("genres", "Frequently Discussed"), + Updates.currentTimestamp("lastUpdated")); + + try { + // Updates documents that have a "num_mflix_comments" value over 50 + UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); + + // Prints the number of updated documents + System.out.println("Modified document count: " + result.getModifiedCount()); + + // Prints a message if any exceptions occur during the operation + } catch (MongoException me) { + System.err.println("Unable to update due to an error: " + me); + } } } } From d4ad22c99fad14b1a3bd1cdddef20af4248877da Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Mon, 24 Feb 2025 15:53:18 -0500 Subject: [PATCH 09/27] modify --- source/crud/bulk.txt | 67 ++++++------------- source/crud/delete.txt | 16 ++--- source/crud/insert.txt | 24 ++++--- source/crud/update-documents.txt | 61 +++++++++++++++-- source/includes/crud/Delete.java | 4 +- source/includes/crud/Insert.java | 4 +- .../code-snippets => crud}/ReplaceOne.java | 0 source/includes/crud/Update.java | 10 +-- .../code-snippets/UpdateMany.java | 48 ------------- 9 files changed, 110 insertions(+), 124 deletions(-) rename source/includes/{usage-examples/code-snippets => crud}/ReplaceOne.java (100%) delete mode 100644 source/includes/usage-examples/code-snippets/UpdateMany.java diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 90ca9ca80..da0f1e661 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -360,8 +360,8 @@ see the following API documentation: - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ -BulkWrite Example -~~~~~~~~~~~~~~~~~ +BulkWrite Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following code is a complete, standalone file that performs an ordered bulk write operation. @@ -622,55 +622,28 @@ Even though the write operation inserting a document with a duplicate key result in an error, the other operations are executed because the write operation is unordered. -To learn more about the methods and classes mentioned in this section, -see the following API documentation: - -- `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ -- `ClientBulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteResult.html>`__ - -Summary -------- - -``MongoCollection.bulkWrite()`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To perform a bulk operation, you create and pass a list of -``WriteModel`` instances to the ``bulkWrite()`` method. - -There are 6 different ``WriteModel`` subtypes: ``InsertOneModel``, -``ReplaceOneModel``, ``UpdateOneModel``, ``UpdateManyModel``, -``DeleteOneModel`` and ``DeleteManyModel``. - -There are two ways to execute the ``bulkWrite()`` method: - -- Ordered, which performs the bulk operations in order until an error occurs, if any -- Unordered, which performs all the bulk operations in any order and reports errors - at the end, if any +API Documentation +----------------- -To learn more about the collection ``bulkWrite`` command, see the -:manual:`db.collection.bulkWrite() ` -method reference in the {+mdb-server+} Manual. +To learn more about the methods and classes used to perform bulk write +operations in this section, see the following API documentation: -``MongoClient.bulkWrite()`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +MongoCollection +~~~~~~~~~~~~~~~ -When connecting to a deployment running {+mdb-server+} version 8.0 or later, you -can use the ``MongoClient.bulkWrite()`` method to perform bulk operations on multiple -databases and collections at once. +- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ +- `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ +- `MongoBulkWriteException <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoBulkWriteException.html>`__ -To perform a client bulk operation, you create an pass a list of -``ClientNamespacedWriteModel`` instances to this method. +MongoClient +~~~~~~~~~~~ -There are six subtypes of ``ClientNamespacedWriteModel`` that are used to -represent write operations. To construct these write models, you can use the -corresponding ``ClientNamespacedWriteModel`` methods ``insertOne()``, ``updateOne()``, -``updateMany()``, ``replaceOne()``, ``deleteOne()``, and ``deleteMany()``. These -methods take a ``MongoNamespace`` object that defines which -database and collection to write to. +- `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCluster.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ +- `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ +- `ClientBulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteResult.html>`__ -The ``MongoClient.bulkWrite()`` method can also take a ``ClientBulkWriteOptions`` -object to specify different options for how the command is executed. +Server Manual Entries +--------------------- -To learn more about the client ``bulkWrite`` command, see the -:manual:`bulkWrite() ` method reference in the {+mdb-server+} -Manual. +- :manual:`MongoCollection.bulkWrite() ` +- :manual:`MongoClient.bulkWrite() ` diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 818ab5701..9c957556d 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -148,8 +148,8 @@ collection: { "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 } -Delete Example --------------- +Delete Example: Full File +------------------------- The following code is a complete, standalone file that performs a delete one operation and a delete many operation. @@ -174,14 +174,10 @@ API documentation. DeleteOne document count: 1 DeleteMany document count: 4 -More Information ----------------- - -For more information about the methods and classes mentioned in this guide, -see the following resources: - API Documentation -~~~~~~~~~~~~~~~~~ +----------------- + +For additional information on the methods and classes used to delete documents, see the following API Documentation: - `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ - `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ @@ -190,7 +186,7 @@ API Documentation - `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ Server Manual Entries -~~~~~~~~~~~~~~~~~~~~~ +--------------------- - :manual:`db.collection.deleteOne() ` - :manual:`db.collection.deleteMany() ` diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 3303c8196..b4753d5ba 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -163,8 +163,8 @@ The output of the preceding code resembles the following: 60930c3aa982931c20ef6cd8] -Insert Example --------------- +Insert Example: Full File +------------------------- The following code is a complete, standalone file that performs an insert one operation and an insert many operation. @@ -184,12 +184,18 @@ operation and an insert many operation. InsertOne document id: BsonObjectId{value=...} InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} -More Information ----------------- +API Documentation +----------------- -For more information about the methods and classes mentioned in this section, -see the following resources: +For additional information on the methods and classes used to insert documents, see the following API Documentation: + +- `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ +- `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ +- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ +- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ + +Server Manual Entries +--------------------- -- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ API Documentation -- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ API Documentation -- Manual Explanation on :manual:`insertMany() ` +- :manual:`db.collection.insertOne() ` +- :manual:`db.collection.insertMany() ` diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 39ae4936c..fb0a93a7d 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -172,8 +172,8 @@ documents match. see :manual:`Unique Indexes ` in the {+mdb-server+} manual. -Update Example -~~~~~~~~~~~~~~ +Update Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~ The following code is a complete, standalone file that performs an update one operation and an update many operation. @@ -190,8 +190,10 @@ operation and an update many operation. :language: none :visible: false - InsertOne document id: BsonObjectId{value=...} - InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} + UpdateOne modified document count: 1 + Upserted ID: null + + UpdateMany modified document count: 242 .. _replace-operation: @@ -286,3 +288,54 @@ documents match. For more information about constraints on unique indexes, see :manual:`Unique Indexes ` in the {+mdb-server+} manual. + +ReplaceOne Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs an update one +operation and an update many operation. + +.. include:: /includes/crud/example-intro.rst + +.. io-code-block:: + + .. input:: /includes/crud/ReplaceOne.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + UpdateOne modified document count: 1 + Upserted ID: null + + UpdateMany modified document count: 242 + +API Documentation +----------------- + +For additional information on the methods and classes used to modify documents, see the following API Documentation: + +- `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ +- `updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ +- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ +- `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ +- `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ +- - `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ + +For additional information on the methods used in the examples on this +page, see the following API Documentation: + +- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ +- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ +- `set() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem)>`__ +- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ +- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ + +Server Manual Entries +--------------------- + +- :manual:`db.collection.updateOne() ` +- :manual:`db.collection.updateMany() ` +- :manual:`db.collection.replaceOne() ` \ No newline at end of file diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index 508d118a9..adf37fdf4 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -14,7 +14,9 @@ import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; -public class DeleteOne { +import static com.mongodb.client.model.Filters.lt; + +public class Delete { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index f8a402648..5c335eac0 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -15,7 +15,9 @@ import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.InsertManyResult; -public class InsertOne { +import java.util.List; + +public class Insert { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = ""; diff --git a/source/includes/usage-examples/code-snippets/ReplaceOne.java b/source/includes/crud/ReplaceOne.java similarity index 100% rename from source/includes/usage-examples/code-snippets/ReplaceOne.java rename to source/includes/crud/ReplaceOne.java diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java index 5f08c7f1e..431afe502 100644 --- a/source/includes/crud/Update.java +++ b/source/includes/crud/Update.java @@ -14,7 +14,9 @@ import com.mongodb.client.model.Updates; import com.mongodb.client.result.UpdateResult; -public class UpdateOne { +import static com.mongodb.client.model.Filters.gt; + +public class Update { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string @@ -41,8 +43,8 @@ public static void main(String[] args) { UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed - System.out.println("Modified document count: " + result.getModifiedCount()); - System.out.println("Upserted id: " + result.getUpsertedId()); + System.out.println("UpdateOne modified document count: " + result.getModifiedCount()); + System.out.println("Upserted ID: " + result.getUpsertedId()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { @@ -61,7 +63,7 @@ public static void main(String[] args) { UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); // Prints the number of updated documents - System.out.println("Modified document count: " + result.getModifiedCount()); + System.out.println("\nUpdateMany modified document count: " + result.getModifiedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { diff --git a/source/includes/usage-examples/code-snippets/UpdateMany.java b/source/includes/usage-examples/code-snippets/UpdateMany.java deleted file mode 100644 index e155cf431..000000000 --- a/source/includes/usage-examples/code-snippets/UpdateMany.java +++ /dev/null @@ -1,48 +0,0 @@ -// Updates documents that match a query filter by using the Java driver - -package usage.examples; - -import static com.mongodb.client.model.Filters.gt; - -import org.bson.Document; -import org.bson.conversions.Bson; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Updates; -import com.mongodb.client.result.UpdateResult; - -public class UpdateMany { - - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - Bson query = gt("num_mflix_comments", 50); - - // Creates instructions to update the values of two document fields - Bson updates = Updates.combine( - Updates.addToSet("genres", "Frequently Discussed"), - Updates.currentTimestamp("lastUpdated")); - - try { - // Updates documents that have a "num_mflix_comments" value over 50 - UpdateResult result = collection.updateMany(query, updates); - - // Prints the number of updated documents - System.out.println("Modified document count: " + result.getModifiedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to update due to an error: " + me); - } - } - } -} From 024cb7697ce5bd7047d7f4597f1e11a3d7bf2732 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Mon, 24 Feb 2025 16:01:40 -0500 Subject: [PATCH 10/27] remove files --- source/crud/insert.txt | 30 ++--- source/crud/update-documents.txt | 2 +- .../crud/{ReplaceOne.java => Replace.java} | 0 .../code-snippets/InsertMany.java | 45 ------- source/usage-examples/insert-operations.txt | 15 --- source/usage-examples/insertMany.txt | 51 ------- source/usage-examples/insertOne.txt | 52 -------- source/usage-examples/replaceOne.txt | 124 ------------------ source/usage-examples/update-operations.txt | 17 --- source/usage-examples/updateMany.txt | 117 ----------------- source/usage-examples/updateOne.txt | 122 ----------------- 11 files changed, 13 insertions(+), 562 deletions(-) rename source/includes/crud/{ReplaceOne.java => Replace.java} (100%) delete mode 100644 source/includes/usage-examples/code-snippets/InsertMany.java delete mode 100644 source/usage-examples/insert-operations.txt delete mode 100644 source/usage-examples/insertMany.txt delete mode 100644 source/usage-examples/insertOne.txt delete mode 100644 source/usage-examples/replaceOne.txt delete mode 100644 source/usage-examples/update-operations.txt delete mode 100644 source/usage-examples/updateMany.txt delete mode 100644 source/usage-examples/updateOne.txt diff --git a/source/crud/insert.txt b/source/crud/insert.txt index b4753d5ba..ca29928a1 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -30,28 +30,22 @@ The following sections focus on ``insertOne()`` and method, see our :ref:`guide on Bulk Operations `. -A Note About ``_id`` --------------------- +.. note:: The ``id_`` field in Insert Operations -When inserting a document, MongoDB enforces one constraint on your -documents by default: each document *must* contain a unique ``_id`` -field. + When inserting a document, MongoDB enforces one constraint on your + documents by default: each document *must* contain a unique ``_id`` + field. Duplicate ``_id`` values violate unique index constraints, resulting in a ``WriteError``. -There are two ways to manage this field: + There are two ways to manage this field: -- You can manage this field yourself, ensuring each value you use is unique. -- You can let the driver automatically generate unique ObjectId values. + - You can manage this field yourself, ensuring each value you use is unique. + - You can let the driver automatically generate unique ObjectId values. -Unless you have provided strong guarantees for uniqueness, we recommend -you let the driver automatically generate ``_id`` values. - -.. note:: - - Duplicate ``_id`` values violate unique index constraints, resulting - in a ``WriteError``. - -For additional information on unique indexes, see the manual entry on -:manual:`Unique Indexes `. + Unless you have provided strong guarantees for uniqueness, we recommend + you let the driver automatically generate ``_id`` values. + + For additional information on unique indexes, see the manual entry on + :manual:`Unique Indexes `. .. _java-insertone: diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index fb0a93a7d..b6e4fb347 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -299,7 +299,7 @@ operation and an update many operation. .. io-code-block:: - .. input:: /includes/crud/ReplaceOne.java + .. input:: /includes/crud/Replace.java :language: java :dedent: diff --git a/source/includes/crud/ReplaceOne.java b/source/includes/crud/Replace.java similarity index 100% rename from source/includes/crud/ReplaceOne.java rename to source/includes/crud/Replace.java diff --git a/source/includes/usage-examples/code-snippets/InsertMany.java b/source/includes/usage-examples/code-snippets/InsertMany.java deleted file mode 100644 index 8575fb7fe..000000000 --- a/source/includes/usage-examples/code-snippets/InsertMany.java +++ /dev/null @@ -1,45 +0,0 @@ -// Inserts sample documents describing movies by using the Java driver - -package usage.examples; - -import java.util.Arrays; -import java.util.List; - -import org.bson.Document; - -import com.mongodb.MongoException; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.result.InsertManyResult; - -public class InsertMany { - - public static void main(String[] args) { - // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; - - try (MongoClient mongoClient = MongoClients.create(uri)) { - MongoDatabase database = mongoClient.getDatabase("sample_mflix"); - MongoCollection collection = database.getCollection("movies"); - - // Creates two sample documents containing a "title" field - List movieList = Arrays.asList( - new Document().append("title", "Short Circuit 3"), - new Document().append("title", "The Lego Frozen Movie")); - - try { - // Inserts sample documents describing movies into the collection - InsertManyResult result = collection.insertMany(movieList); - - // Prints the IDs of the inserted documents - System.out.println("Inserted document ids: " + result.getInsertedIds()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to insert due to an error: " + me); - } - } - } -} diff --git a/source/usage-examples/insert-operations.txt b/source/usage-examples/insert-operations.txt deleted file mode 100644 index 0c4b9975e..000000000 --- a/source/usage-examples/insert-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -================= -Insert Operations -================= - -.. meta:: - :description: Learn by example: how to insert data into MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Insert One - Insert Many - -- :doc:`Insert a Document ` -- :doc:`Insert Multiple Documents ` diff --git a/source/usage-examples/insertMany.txt b/source/usage-examples/insertMany.txt deleted file mode 100644 index 303238958..000000000 --- a/source/usage-examples/insertMany.txt +++ /dev/null @@ -1,51 +0,0 @@ -.. _java-usage-insertmany: - -========================= -Insert Multiple Documents -========================= - - - -You can insert multiple documents into a collection in a single -operation by calling the ``insertMany()`` method on a ``MongoCollection`` -object. To insert them, add your ``Document`` objects to a ``List`` and pass -that ``List`` as an argument to ``insertMany()``. If you call the ``insertMany()`` method -on a collection that does not exist yet, the server creates it for you. - -Upon successful insertion, ``insertMany()`` returns an instance of -``InsertManyResult``. You can retrieve information such as the ``_id`` -fields of the documents you inserted by calling the ``getInsertedIds()`` -method on the ``InsertManyResult`` instance. - -If your insert operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``insertMany()``, linked at the bottom of -this page. - -Example -------- - -The following snippet inserts multiple documents into the ``movies`` -collection. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/InsertMany.java - :language: java - -When you run the example, you should see output that resembles the following -with the inserted documents' ``ObjectId`` values in each of the value fields: - -.. code-block:: none - :copyable: false - - Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ -- `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ -- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ diff --git a/source/usage-examples/insertOne.txt b/source/usage-examples/insertOne.txt deleted file mode 100644 index 203683884..000000000 --- a/source/usage-examples/insertOne.txt +++ /dev/null @@ -1,52 +0,0 @@ -.. _java-usage-insertone: - -================= -Insert a Document -================= - - - -You can insert a single document into a collection using the ``insertOne()`` -method on a ``MongoCollection`` object. To insert a document, construct a -``Document`` object that contains the fields and values that you want to -store. If you call the ``insertOne()`` method on a collection that does -not exist yet, the server automatically creates it for you. - -Upon a successful insertion, ``insertOne()`` returns an instance of -``InsertOneResult``. You can retrieve information such as the ``_id`` -field of the document you inserted by calling the ``getInsertedId()`` -method on the ``InsertOneResult`` instance. - -If your insert operation fails, the driver raises an exception. For more -information on the types of exceptions raised under specific conditions, -see the API documentation for ``insertOne()``, linked at the bottom of -this page. - -Example -------- - -The following snippet inserts a single document into the ``movies`` -collection. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/InsertOne.java - :language: java - -When you run the example, you should see output that resembles the following -with the inserted document's ``ObjectId`` in the value field: - -.. code-block:: none - :copyable: false - - Inserted document id: BsonObjectId{value=...} - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ -- `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ -- `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ - diff --git a/source/usage-examples/replaceOne.txt b/source/usage-examples/replaceOne.txt deleted file mode 100644 index 62c6b5402..000000000 --- a/source/usage-examples/replaceOne.txt +++ /dev/null @@ -1,124 +0,0 @@ -.. _java-usage-replaceone: - -================== -Replace a Document -================== - - - -You can replace a single document using the ``replaceOne()`` method on -a ``MongoCollection`` object. This method removes all the existing fields -and values from a document (except the ``_id`` field) and substitutes it -with your replacement document. - -The ``replaceOne()`` method accepts a query filter that matches the -document you want to replace and a replacement document that contains the -data you want to save in place of the matched document. The ``replaceOne()`` -method only replaces the first document that matches the filter. - -You can optionally pass an instance of ``ReplaceOptions`` to the ``replaceOne()`` method in -order to specify the method's behavior. For example, if you set the ``upsert`` -field of the ``ReplaceOptions`` object to ``true``, the operation inserts -a new document from the fields in the replacement document if no documents -match the query filter. See the link to the ``ReplaceOptions`` API -documentation at the bottom of this page for more information. - -Upon successful execution, the ``replaceOne()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method. You can also -retrieve the value of the document's ``_id`` field by calling the -``getUpsertedId()`` method if you set ``upsert(true)`` in the -``ReplaceOptions`` instance and the operation resulted in the insertion of a new document. - -If your replacement operation fails, the driver raises an exception. -For example, if you try to specify a value for the immutable field -``_id`` in your replacement document that differs from the original -document, the method throws a ``MongoWriteException`` with the message: - -.. code-block:: none - :copyable: false - - After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...) - -If your replacement document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``replaceOne()``, linked at the -bottom of this page. - -Example -------- - -In this example, we replace the first match of our query filter in the -``movies`` collection of the ``sample_mflix`` database with a replacement -document. All the fields except for the ``_id`` field are deleted from the -original document and are substituted by the replacement document. - -Before the ``replaceOne()`` operation runs, the original document contains -several fields describing the movie. After the operation runs, the resulting -document contains only the fields specified by the replacement document -(``title`` and ``fullplot``) and the ``_id`` field. - -The following snippet uses the following objects and methods: - -- A **query filter** that is passed to the ``replaceOne()`` method. The ``eq`` - filter matches only movies with the title exactly matching the text - ``'Music of the Heart'``. - -- A **replacement document** that contains the document that replaces the - matching document if it exists. - -- A **ReplaceOptions** object with the ``upsert`` option set to ``true``. - This option specifies that the method should insert the data contained in - the replacement document if the query filter does not match any documents. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/ReplaceOne.java - :language: java - -After you run the example, you should see output that looks something like -this: - -.. code-block:: none - :copyable: false - - Modified document count: 1 - Upserted id: null - -Or if the example resulted in an upsert: - -.. code-block:: none - :copyable: false - - Modified document count: 0 - Upserted id: BsonObjectId{value=...} - -If you query the replaced document, the output resembles the following: - -.. code-block:: none - :copyable: false - - Document { - { _id=..., - title=50 Violins, - fullplot=A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music - } - } - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `ReplaceOne <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ -- `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ -- `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ diff --git a/source/usage-examples/update-operations.txt b/source/usage-examples/update-operations.txt deleted file mode 100644 index 0f8e93d37..000000000 --- a/source/usage-examples/update-operations.txt +++ /dev/null @@ -1,17 +0,0 @@ -=========================== -Update & Replace Operations -=========================== - -.. meta:: - :description: Learn by example: how to update and replace data in MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Update One - Update Many - Replace One - -- :doc:`Update a Document ` -- :doc:`Update Multiple Documents ` -- :doc:`Replace a Document ` diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt deleted file mode 100644 index cbdc791dd..000000000 --- a/source/usage-examples/updateMany.txt +++ /dev/null @@ -1,117 +0,0 @@ -.. _java-usage-updatemany: - -========================= -Update Multiple Documents -========================= - - - -You can update multiple documents using the ``updateMany()`` method on -a ``MongoCollection`` object. The method accepts a **filter** that matches the -document you want to update and an **update** statement that instructs the -driver how to change the matching document. The ``updateMany()`` method updates -all the documents in the collection that match the filter. - -To perform an update with the ``updateMany()`` method, you must pass -a query filter and an update document. The query filter specifies which -documents in the collection to match and the update document provides -instructions on what changes to make to them. - -You can optionally pass an instance of ``UpdateOptions`` to the ``updateMany()`` method in -order to modify the behavior of the call. For example, if you set the -``upsert`` field of the ``UpdateOptions`` object to ``true`` and no documents -match the specified query filter, the operation inserts a new document -composed of the fields from both the query and update document. - -Upon successful execution, the ``updateMany()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method. If you -specified ``upsert(true)`` in an ``UpdateOptions`` object and the -operation results in an insert, you can retrieve the ``_id`` field of the -new document by calling the ``getUpsertedId()`` method on the -``UpdateResult`` instance. - -If your update operation fails, the driver raises an exception and does not update -any of the documents matching the filter. For example, if you try to set -a value for the immutable field ``_id`` in your update document, the -``updateMany()`` method does not update any documents and throws a -``MongoWriteException`` with the message: - -.. code-block:: none - :copyable: false - - Performing an update on the path '_id' would modify the immutable field '_id' - -If your update document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``updateMany()``, linked at the -bottom of this page. - -Example -------- - -In this example, we update documents that match our query in the ``movies`` -collection of the ``sample_mflix`` database. We perform the following -updates to the matching documents: - -- Add ``Frequently Discussed`` to the array of ``genres`` only if it does not - already exist -- Set the value of ``lastUpdated`` to the current time. - -We use the ``Updates`` builder, a factory class that contains static -helper methods to construct the update document. While you can pass an update -document instead of using the builder, the builder provides type checking and -simplified syntax. Read our -:ref:`guide on Updates ` in the Builders -section for more information. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/UpdateMany.java - :language: java - -After you run the example, you should see output that looks something like -this: - -.. code-block:: none - :copyable: false - - Modified document count: 53 - -If you query the updated document or documents, they should look something like -this: - -.. code-block:: none - :copyable: false - - [ - Document { - { _id=..., - plot=..., - genres=[..., Frequently Discussed, ...], - ... - lastUpdated=Timestamp{...} - } - }, - ... - ] - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `UpdateMany <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ -- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ -- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ -- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ -- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt deleted file mode 100644 index 8aba7942d..000000000 --- a/source/usage-examples/updateOne.txt +++ /dev/null @@ -1,122 +0,0 @@ -.. _java-usage-updateone: - -================= -Update a Document -================= - - - -You can update a single document using the ``updateOne()`` method on -a ``MongoCollection`` object. The method accepts a **filter** that matches the -document you want to update and an **update** statement that instructs the -driver how to change the matching document. The ``updateOne()`` method only -updates the first document that matches the filter. - -To perform an update with the ``updateOne()`` method, you must pass -a query filter and an update document. The query filter specifies the criteria -for which document to perform the update on and the update document provides -instructions on what changes to make to it. - -You can optionally pass an instance of ``UpdateOptions`` to the ``updateOne()`` method in -order to specify the method's behavior. For example, if you set the ``upsert`` field of -the ``UpdateOptions`` object to ``true``, the operation inserts a new -document from the fields in both the query and update document if no documents -match the query filter. See the link to the ``UpdateOptions`` API -documentation at the bottom of this page for more information. - -Upon successful execution, the ``updateOne()`` method returns an instance -of ``UpdateResult``. You can retrieve information such as the number of -documents modified by calling the ``getModifiedCount()`` method, or the -value of the ``_id`` field by calling the ``getUpsertedId()`` method if you -specified ``upsert(true)`` in an ``UpdateOptions`` instance. - -If your update operation fails, the driver raises an exception. -For example, if you try to set a value for the immutable field ``_id`` in -your update document, the method throws a ``MongoWriteException`` with the -message: - -.. code-block:: none - :copyable: false - - Performing an update on the path '_id' would modify the immutable field '_id' - -If your update document contains a change that violates unique index -rules, the method throws a ``MongoWriteException`` with an error -message that resembles the following: - -.. code-block:: none - :copyable: false - - E11000 duplicate key error collection: ... - -For more information about the types of exceptions raised under specific -conditions, see the API documentation for ``updateOne()``, linked at the -bottom of this page. - -Example -------- - -In this example, we update the first match for our query in the ``movies`` -collection of the ``sample_mflix`` database. We perform the following -updates to the matching document: - -- Set the value of ``runtime`` to ``99`` -- Add ``Sports`` to the array of ``genres`` only if it does not already - exist -- Set the value of ``lastUpdated`` to the current time. - -We use the ``Updates`` builder, a factory class that contains static -helper methods, to construct the update document. While you can pass an update -document instead of using the builder, the builder provides type checking and -simplified syntax. For more information about the ``Updates`` builder, see our -:ref:`guide about Updates `. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/UpdateOne.java - :language: java - -After you run the example, you should see output that looks something like this: - -.. code-block:: none - :copyable: false - - Modified document count: 1 - Upserted id: null - -Or if the example resulted in an upsert: - -.. code-block:: none - :copyable: false - - Modified document count: 0 - Upserted id: BsonObjectId{value=...} - - -If you query the updated document, the output resembles the following: - -.. code-block:: none - :copyable: false - - Document { - { _id=..., - plot=..., - genres=[Adventure, Comedy, Family, Sports], - runtime=99, - ... - lastUpdated=Timestamp{...} - } - } - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `UpdateOne <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ -- `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ -- `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ -- `set() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem)>`__ -- `addToSet() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#addToSet(java.lang.String,TItem)>`__ -- `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ -- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ From 1b43c376fb26e852c0cfb8693cb5dffa53a01238 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 09:46:29 -0500 Subject: [PATCH 11/27] retrieve --- source/crud/delete.txt | 5 +- source/crud/query-documents/find.txt | 55 ++++++++++++++++--- source/crud/update-documents.txt | 9 ++- .../code-snippets => crud}/Find.java | 25 ++++++--- .../crud/{Replace.java => ReplaceOne.java} | 0 5 files changed, 71 insertions(+), 23 deletions(-) rename source/includes/{usage-examples/code-snippets => crud}/Find.java (65%) rename source/includes/crud/{Replace.java => ReplaceOne.java} (100%) diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 9c957556d..6cc782633 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -184,10 +184,11 @@ For additional information on the methods and classes used to delete documents, - `findOneAndDelete() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndDelete(org.bson.conversions.Bson)>`__ - `DeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/DeleteOptions.html>`__ - `FindOneAndDeleteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/FindOneAndDeleteOptions.html>`__ +- `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ Server Manual Entries --------------------- -- :manual:`db.collection.deleteOne() ` -- :manual:`db.collection.deleteMany() ` +- :manual:`db.collection.deleteOne() ` +- :manual:`db.collection.deleteMany() ` - :manual:`db.collection.findOneAndDelete() ` diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index a738def52..018d66238 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -4,6 +4,14 @@ Find Documents ============== +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: find, findOne, findMany, get, lookup + :description: Learn about how to retrieve data in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none @@ -80,8 +88,27 @@ The following shows the output of the preceding query: After the owner runs this query, they find two orders that matched the criteria. -For a runnable ``find()`` example, see our :ref:`Find Multiple -Documents ` page. +Find Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs a find one +operation and a find many operation. + +.. include:: /includes/crud/example-intro.rst + +.. io-code-block:: + + .. input:: /includes/crud/Find.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Number of documents found with find(): 101 + + Document found with find().first(){"title": "The Room", "imdb": {"rating": 3.5, "votes": 25673, "id": 368226}} .. _retrieve-aggregate: @@ -97,7 +124,8 @@ instance of a ``MongoCollection``. This method accepts aggregation expressions to run in sequence. To perform aggregations, you can define aggregation stages that specify how to match documents, rename fields, and group values. For more information, see our -:ref:`Aggregation ` guide. +:ref:`Aggregation ` guide and the :ref:`Aggregation Expression +Operations ` page. Example ~~~~~~~ @@ -132,8 +160,21 @@ purchased color. For more information about how to construct an aggregation pipeline, see the {+mdb-server+} manual page on :manual:`Aggregation `. -For additional information on the methods mentioned on this page, see -the following API Documentation: +API Documentation +----------------- + +For additional information on the methods and classes used to retrieve documents +on this page, see the following API Documentation: + +- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ +- `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ +- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ +- `aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ + +Server Manual Entries +--------------------- -- `MongoCollection.find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ -- `MongoCollection.aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ +- :manual:`Collections ` +- :manual:`Query Documents ` +- :manual:`Aggregation ` +- :manual:`Aggregation stages ` diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index b6e4fb347..8e555f554 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -182,7 +182,7 @@ operation and an update many operation. .. io-code-block:: - .. input:: /includes/crud/Insert.java + .. input:: /includes/crud/Update.java :language: java :dedent: @@ -292,14 +292,13 @@ documents match. ReplaceOne Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following code is a complete, standalone file that performs an update one -operation and an update many operation. +The following code is a complete, standalone file that performs a replace one operation. .. include:: /includes/crud/example-intro.rst .. io-code-block:: - .. input:: /includes/crud/Replace.java + .. input:: /includes/crud/ReplaceOne.java :language: java :dedent: @@ -322,7 +321,7 @@ For additional information on the methods and classes used to modify documents, - `UpdateOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/UpdateOptions.html>`__ - `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ - `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ -- - `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ +- `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ For additional information on the methods used in the examples on this page, see the following API Documentation: diff --git a/source/includes/usage-examples/code-snippets/Find.java b/source/includes/crud/Find.java similarity index 65% rename from source/includes/usage-examples/code-snippets/Find.java rename to source/includes/crud/Find.java index 596089b55..36352f768 100644 --- a/source/includes/usage-examples/code-snippets/Find.java +++ b/source/includes/crud/Find.java @@ -1,7 +1,4 @@ // Retrieves documents that match a query filter by using the Java driver - -package usage.examples; - import static com.mongodb.client.model.Filters.lt; import org.bson.Document; @@ -15,6 +12,8 @@ import com.mongodb.client.model.Projections; import com.mongodb.client.model.Sorts; +import static com.mongodb.client.model.Filters.eq; + public class Find { public static void main( String[] args ) { @@ -36,12 +35,20 @@ public static void main( String[] args ) { .sort(Sorts.descending("title")).iterator(); // Prints the results of the find operation as JSON - try { - while(cursor.hasNext()) { - System.out.println(cursor.next().toJson()); - } - } finally { - cursor.close(); + System.out.println("Number of documents found with find(): " + cursor.available() + "\n"); + cursor.close(); + + // Retrieves the first matching document, applying a projection and a descending sort to the results + Document doc = collection.find(eq("title", "The Room")) + .projection(projectionFields) + .sort(Sorts.descending("imdb.rating")) + .first(); + + // Prints a message if there are no result documents, or prints the result document as JSON + if (doc == null) { + System.out.println("No results found."); + } else { + System.out.println("Document found with find().first()" + doc.toJson()); } } } diff --git a/source/includes/crud/Replace.java b/source/includes/crud/ReplaceOne.java similarity index 100% rename from source/includes/crud/Replace.java rename to source/includes/crud/ReplaceOne.java From 3ca98c292557671bef73035e226179d0239c9d86 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 10:26:17 -0500 Subject: [PATCH 12/27] clean up --- source/crud/query-documents/find.txt | 8 ++- source/usage-examples/find-operations.txt | 15 ----- source/usage-examples/find.txt | 77 ----------------------- source/usage-examples/findOne.txt | 69 -------------------- 4 files changed, 6 insertions(+), 163 deletions(-) delete mode 100644 source/usage-examples/find-operations.txt delete mode 100644 source/usage-examples/find.txt delete mode 100644 source/usage-examples/findOne.txt diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 018d66238..7fe410353 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -60,6 +60,9 @@ match the query filter you provide. For more information about how to specify a query, see our :ref:`Specify a Query ` guide. +To retrieve a single document, you can append the ``first()`` method to your +``find()`` operation. + Example ~~~~~~~ @@ -91,8 +94,9 @@ criteria. Find Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~ -The following code is a complete, standalone file that performs a find one -operation and a find many operation. +The following code is a complete, standalone file that performs a find +operation to retrieve multiple douments, and a find operation with the first +method to retrieve a single document. .. include:: /includes/crud/example-intro.rst diff --git a/source/usage-examples/find-operations.txt b/source/usage-examples/find-operations.txt deleted file mode 100644 index 712144c6d..000000000 --- a/source/usage-examples/find-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -=============== -Find Operations -=============== - -.. meta:: - :description: Learn by example: how to create queries and retrieve data from MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Find One - Find Many - -- :doc:`Find a Document ` -- :doc:`Find Multiple Documents ` diff --git a/source/usage-examples/find.txt b/source/usage-examples/find.txt deleted file mode 100644 index d5ee25489..000000000 --- a/source/usage-examples/find.txt +++ /dev/null @@ -1,77 +0,0 @@ -.. _java-usage-find: - -======================= -Find Multiple Documents -======================= - - - -You can query for multiple documents in a collection by calling the ``find()`` -method on a ``MongoCollection`` object. Pass a query filter to the -``find()`` method to query for and return documents that match the filter in -the collection. If you do not include a filter, MongoDB returns all the -documents in the collection. - -For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. - -You can also chain methods to the ``find()`` method such as ``sort()`` which -organizes the matched documents in a specified order and -``projection()`` which configures the included fields in the -returned documents. - -For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. -For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` - -The ``find()`` method returns an instance of ``FindIterable``, a class -that offers several methods to access, organize, and traverse the results. -``FindIterable`` also inherits methods from its parent class, -``MongoIterable`` which implements the core Java interface ``Iterable``. - -You can call the ``iterator()`` method on the ``MongoIterable`` which -returns a ``MongoCursor`` instance that you can use to traverse the results. -You can call methods on the ``MongoCursor`` such as ``hasNext()`` to check -whether additional results exist, or ``next()`` to return the next document -in the collection. If no documents match the query, calling ``hasNext()`` -returns ``false`` and therefore calling ``next()`` throws an exception. - -If you call ``next()`` on the iterator either after it has returned the final -result or when no results exist, it throws an exception of type -``java.util.NoSuchElementException``. Always use ``hasNext()`` to check that -additional results exist before you call ``next()``. - - -Example -------- - -The following snippet finds and prints all documents that match a query on -the ``movies`` collection. It uses the following objects and methods: - -- A **query filter** that is passed to the ``find()`` method. The ``lt()`` - filter matches only movies with a runtime of less than 15 minutes. - -- A **sort** that organizes returned documents in descending order by - title ("Z" before "A"). - -- A **projection** that includes the objects in the ``title`` and ``imdb`` - fields and excludes the ``_id`` field using the helper method - ``excludeId()``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/Find.java - :language: java - - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ -- `MongoIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html>`__ -- `MongoCursor <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html>`__ -- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ - diff --git a/source/usage-examples/findOne.txt b/source/usage-examples/findOne.txt deleted file mode 100644 index f6bfd7366..000000000 --- a/source/usage-examples/findOne.txt +++ /dev/null @@ -1,69 +0,0 @@ -.. _java-usage-findone: - -=============== -Find a Document -=============== - - - -You can retrieve a single document in a collection by chaining together -the ``find()`` and ``first()`` methods on a ``MongoCollection`` object. -You can pass a query filter to the ``find()`` method to query for and -return documents that match the filter in the collection. If you do not -include a filter, MongoDB returns all the documents in the collection. The -``first()`` method returns the first matching document. - -For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. - -You can also chain other methods to the ``find()`` method -such as ``sort()`` which organizes the matched documents in a specified order, and -``projection()`` which configures the fields included in the returned documents. - -For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. -For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` - -The ``find()`` method returns an instance of ``FindIterable``, a class -that offers several methods to access, organize, and traverse the results. -``FindIterable`` also inherits methods from its parent class, -``MongoIterable`` such as ``first()``. - -The ``first()`` method returns the first document from the retrieved results -or ``null`` if there are no results. - - -Example -------- - -The following snippet finds a single document from the ``movies`` collection. -It uses the following objects and methods: - -- A **query filter** that is passed to the ``find()`` method. The ``eq`` - filter matches only movies with the title exactly matching the text - ``'The Room'``. - -- A **sort** that organizes matched documents in descending order by - rating, so if our query matches multiple documents the returned - document is the one with the highest rating. - -- A **projection** that includes the objects in the ``title`` and ``imdb`` - fields and excludes the ``_id`` field using the helper method - ``excludeId()``. - -.. include:: /includes/connect-guide-note.rst - -.. literalinclude:: /includes/usage-examples/code-snippets/FindOne.java - :language: java - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: - -- `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ -- `MongoIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html>`__ -- `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ -- `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ - From d097e5f6bd453b261947c3cc08dadd5daa9a44d8 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 11:19:39 -0500 Subject: [PATCH 13/27] readd BulkWrite snippets --- .../fundamentals/code-snippets/BulkWrite.java | 257 ++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 source/includes/fundamentals/code-snippets/BulkWrite.java diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java new file mode 100644 index 000000000..52f806b73 --- /dev/null +++ b/source/includes/fundamentals/code-snippets/BulkWrite.java @@ -0,0 +1,257 @@ +package docs; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.model.ReplaceOneModel; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.DeleteOneModel; +import com.mongodb.client.model.DeleteManyModel; + +import com.mongodb.MongoBulkWriteException; + +import org.bson.Document; + +import java.util.*; + +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import com.mongodb.client.model.WriteModel; + +public class BulkWrite { + + private final MongoCollection collection; + private final MongoClient mongoClient; + private final MongoDatabase database; + + private BulkWrite() { + final String uri = System.getenv("DRIVER_REF_URI"); + + mongoClient = MongoClients.create(uri); + database = mongoClient.getDatabase("crudOps"); + collection = database.getCollection("bulkWrite"); + } + + public static void main(String[] args) { + BulkWrite bulkWrite = new BulkWrite(); + System.out.println("Ordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteExample(); + bulkWrite.preview(); + + System.out.println("Unordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteNotOrderedExample(); + bulkWrite.preview(); + + System.out.println("Insert BulkWriteException"); + bulkWrite.setUpCollection(); + bulkWrite.insertExceptionExample(); + + System.out.println("Insert"); + bulkWrite.setUpCollection(); + bulkWrite.insertDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Replace"); + bulkWrite.setUpCollection(); + bulkWrite.replaceDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Update"); + bulkWrite.setUpCollection(); + bulkWrite.updateDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Delete"); + bulkWrite.setUpCollection(); + bulkWrite.deleteDocumentsExample(); + bulkWrite.preview(); + } + + + private void insertExceptionExample() { + // begin insertExceptionExample + try { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert documents + InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); + InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); + + bulkOperations.add(doc1); + bulkOperations.add(doc3); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + + // Prints a message if any exceptions occur during the bulk write operation + } catch (MongoBulkWriteException e){ + System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); + } + //end insertExceptionExample + } + + private void bulkWriteNotOrderedExample() { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // Creates instructions to replace the first document that matches the query + ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), + new Document("name", "Sandy Kane") + .append("location", "Helena, MT")); + + // Creates instructions to update the first document that matches the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents that match the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // begin bulkWriteNotOrderedExample + BulkWriteOptions options = new BulkWriteOptions().ordered(false); + + // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order + collection.bulkWrite(bulkOperations, options); + //end bulkWriteNotOrderedExample + } + + private void bulkWriteExample() { + // begin bulkWriteExample + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // 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 first document matched by the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents matched by the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order + collection.bulkWrite(bulkOperations); + //end bulkWriteExample + } + + private void insertDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert multiple documents + // begin insertDocumentsExample + InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") + .append("age", 17)); + + InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") + .append("age", 22)); + //end insertDocumentsExample + + bulkOperations.add(juneDoc); + bulkOperations.add(kevinDoc); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + } + + private void replaceDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to replace the first document matched by the query + // begin replaceDocumentsExample + ReplaceOneModel celineDoc = new ReplaceOneModel<>( + Filters.eq("_id", 1), + new Document("name", "Celine Stork") + .append("location", "San Diego, CA")); + //end replaceDocumentsExample + + bulkOperations.add(celineDoc); + + // Runs a bulk write operation for the specified replace WriteModel + collection.bulkWrite(bulkOperations); + } + + private void updateDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to update the first document matched by the query + // begin updateDocumentsExample + UpdateOneModel updateDoc = new UpdateOneModel<>( + Filters.eq("_id", 2), + Updates.set("age", 31)); + //end updateDocumentsExample + + bulkOperations.add(updateDoc); + + // Runs a bulk write operation for the specified update WriteModel + collection.bulkWrite(bulkOperations); + } + + private void deleteDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to delete the first document matched by the query + // begin deleteDocumentsExample + DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); + //end deleteDocumentsExample + + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified delete WriteModel + collection.bulkWrite(bulkOperations); + } + + private void preview(){ + collection.find().forEach(doc -> System.out.println(doc.toJson())); + } + + private void setUpCollection(){ + collection.drop(); + + //begin bulkOpsList + List> bulkOperations = new ArrayList<>(); + //end bulkOpsList + + InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) + .append("name", "Karen Sandoval") + .append("age", 31)); + + InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) + .append("name", "William Chin") + .append("age", 54)); + + InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) + .append("name", "Shayla Ray") + .append("age", 20)); + + bulkOperations.add(karen); + bulkOperations.add(william); + bulkOperations.add(shayla); + + collection.bulkWrite(bulkOperations); + } +} From 503335d2466f85371d7222c2456f48d59b446715 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 11:31:04 -0500 Subject: [PATCH 14/27] vale --- source/crud/delete.txt | 2 +- source/crud/insert.txt | 4 ++-- source/crud/query-documents/find.txt | 2 +- source/crud/update-documents.txt | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 6cc782633..acbf0d95e 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -177,7 +177,7 @@ API documentation. API Documentation ----------------- -For additional information on the methods and classes used to delete documents, see the following API Documentation: +For more information on the methods and classes used to delete documents, see the following API Documentation: - `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ - `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ diff --git a/source/crud/insert.txt b/source/crud/insert.txt index ca29928a1..c35a0efee 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -44,7 +44,7 @@ method, see our Unless you have provided strong guarantees for uniqueness, we recommend you let the driver automatically generate ``_id`` values. - For additional information on unique indexes, see the manual entry on + For more information on unique indexes, see the manual entry on :manual:`Unique Indexes `. .. _java-insertone: @@ -181,7 +181,7 @@ operation and an insert many operation. API Documentation ----------------- -For additional information on the methods and classes used to insert documents, see the following API Documentation: +For more information on the methods and classes used to insert documents, see the following API Documentation: - `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ - `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 7fe410353..e8f609d3c 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -167,7 +167,7 @@ the {+mdb-server+} manual page on :manual:`Aggregation `. API Documentation ----------------- -For additional information on the methods and classes used to retrieve documents +For more information on the methods and classes used to retrieve documents on this page, see the following API Documentation: - `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 8e555f554..6a6adc42f 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -314,7 +314,7 @@ The following code is a complete, standalone file that performs a replace one op API Documentation ----------------- -For additional information on the methods and classes used to modify documents, see the following API Documentation: +For more information on the methods and classes used to modify documents, see the following API Documentation: - `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ - `updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ @@ -323,7 +323,7 @@ For additional information on the methods and classes used to modify documents, - `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ - `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ -For additional information on the methods used in the examples on this +For more information on the methods used in the examples on this page, see the following API Documentation: - `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ From d50e0234b6e3685c375d6a9d8d5a71551bc89dc4 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 16:10:38 -0500 Subject: [PATCH 15/27] NR feedback --- source/crud/bulk.txt | 26 +++++++++++++++----------- source/crud/delete.txt | 24 ++++++++++++++---------- source/crud/insert.txt | 22 +++++++++++++--------- source/crud/query-documents/find.txt | 28 +++++++++++++++++----------- source/crud/update-documents.txt | 17 ++++++++++------- source/includes/crud/Delete.java | 4 ++-- source/includes/crud/Find.java | 2 +- source/includes/crud/Insert.java | 4 ++-- 8 files changed, 74 insertions(+), 53 deletions(-) diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index da0f1e661..62e950bd3 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -360,16 +360,17 @@ see the following API documentation: - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ -BulkWrite Example: Full File -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following code is a complete, standalone file that performs an ordered bulk -write operation. +Bulk Write Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/crud/example-intro.rst -This example call to ``bulkWrite()`` includes examples of the ``InsertOneModel``, -``UpdateOneModel``, ``DeleteOneModel``, and ``ReplaceOneModel``. +The following code is a complete, standalone file that performs the following +actions: + +#. Creates a list of instances of the ``InsertOneModel``, ``UpdateOneModel``, + ``DeleteOneModel``, and ``ReplaceOneModel`` classes. +#. Runs an ordered ``bulkWrite()`` operation on the list. .. io-code-block:: @@ -622,28 +623,31 @@ Even though the write operation inserting a document with a duplicate key result in an error, the other operations are executed because the write operation is unordered. +Additional Information +---------------------- + API Documentation ------------------ +~~~~~~~~~~~~~~~~~ To learn more about the methods and classes used to perform bulk write operations in this section, see the following API documentation: MongoCollection -~~~~~~~~~~~~~~~ +``````````````` - `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ - `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ - `MongoBulkWriteException <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoBulkWriteException.html>`__ MongoClient -~~~~~~~~~~~ +```````````` - `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCluster.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ - `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ - `ClientBulkWriteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteResult.html>`__ Server Manual Entries ---------------------- +~~~~~~~~~~~~~~~~~~~~~ - :manual:`MongoCollection.bulkWrite() ` - :manual:`MongoClient.bulkWrite() ` diff --git a/source/crud/delete.txt b/source/crud/delete.txt index acbf0d95e..ce5b2fb2d 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -151,15 +151,10 @@ collection: Delete Example: Full File ------------------------- -The following code is a complete, standalone file that performs a delete one -operation and a delete many operation. - .. include:: /includes/crud/example-intro.rst -The query uses the ``eq()`` and ``lt()`` filters to query documents. For more -information about filters, see the `Filters Class -<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ -API documentation. +The following code is a complete, standalone file that performs a delete one +operation and a delete many operation. .. io-code-block:: @@ -174,10 +169,19 @@ API documentation. DeleteOne document count: 1 DeleteMany document count: 4 + +The query in this examples uses the ``eq()`` and ``lt()`` filters to query documents. For more +information about filters, see the `Filters Class +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ +API documentation. + +Additional Information +---------------------- + API Documentation ------------------ +~~~~~~~~~~~~~~~~~ -For more information on the methods and classes used to delete documents, see the following API Documentation: +For more information about the methods and classes used to delete documents, see the following API cocumentation: - `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ - `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ @@ -187,7 +191,7 @@ For more information on the methods and classes used to delete documents, see th - `DeleteResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/DeleteResult.html>`__ Server Manual Entries ---------------------- +~~~~~~~~~~~~~~~~~~~~~ - :manual:`db.collection.deleteOne() ` - :manual:`db.collection.deleteMany() ` diff --git a/source/crud/insert.txt b/source/crud/insert.txt index c35a0efee..1ff7e3719 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -30,11 +30,12 @@ The following sections focus on ``insertOne()`` and method, see our :ref:`guide on Bulk Operations `. -.. note:: The ``id_`` field in Insert Operations +.. note:: The ``id_`` Field in Insert Operations When inserting a document, MongoDB enforces one constraint on your - documents by default: each document *must* contain a unique ``_id`` - field. Duplicate ``_id`` values violate unique index constraints, resulting in a ``WriteError``. + documents by default: each document *must* contain a unique ``_id`` value. + Duplicate ``_id`` values violate unique index constraints, resulting in a + ``WriteError``. There are two ways to manage this field: @@ -44,7 +45,7 @@ method, see our Unless you have provided strong guarantees for uniqueness, we recommend you let the driver automatically generate ``_id`` values. - For more information on unique indexes, see the manual entry on + For more information about unique indexes, see the manual entry on :manual:`Unique Indexes `. .. _java-insertone: @@ -160,11 +161,11 @@ The output of the preceding code resembles the following: Insert Example: Full File ------------------------- +.. include:: /includes/crud/example-intro.rst + The following code is a complete, standalone file that performs an insert one operation and an insert many operation. -.. include:: /includes/crud/example-intro.rst - .. io-code-block:: .. input:: /includes/crud/Insert.java @@ -178,10 +179,13 @@ operation and an insert many operation. InsertOne document id: BsonObjectId{value=...} InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} +Additional Information +---------------------- + API Documentation ------------------ +~~~~~~~~~~~~~~~~~ -For more information on the methods and classes used to insert documents, see the following API Documentation: +For more information about the methods and classes used to insert documents, see the following API cocumentation: - `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ - `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ @@ -189,7 +193,7 @@ For more information on the methods and classes used to insert documents, see th - `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ Server Manual Entries ---------------------- +~~~~~~~~~~~~~~~~~~~~~ - :manual:`db.collection.insertOne() ` - :manual:`db.collection.insertMany() ` diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index e8f609d3c..01da8d95c 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -15,7 +15,7 @@ Find Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -61,7 +61,8 @@ specify a query, see our :ref:`Specify a Query ` guide. To retrieve a single document, you can append the ``first()`` method to your -``find()`` operation. +``find()`` operation. You can use the ``sort()`` operation before selecting the first +document to help choose the correct file. Example ~~~~~~~ @@ -94,12 +95,14 @@ criteria. Find Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~ -The following code is a complete, standalone file that performs a find -operation to retrieve multiple douments, and a find operation with the first -method to retrieve a single document. - .. include:: /includes/crud/example-intro.rst +The following code is a complete, standalone file that performs the following +actions: + +- Calls the ``find()`` method to retrieve multiple documents that have a ``runtime`` value less than 15, applying a projection and sort to the results +- Calls the ``find()`` and ``first()`` method to retrieve a document that has a ``title`` value of ``"The Room"``, applying a projection and sort before returning the first match + .. io-code-block:: .. input:: /includes/crud/Find.java @@ -112,7 +115,7 @@ method to retrieve a single document. Number of documents found with find(): 101 - Document found with find().first(){"title": "The Room", "imdb": {"rating": 3.5, "votes": 25673, "id": 368226}} + Document found with find().first(): {"title": "The Room", "imdb": {"rating": 3.5, "votes": 25673, "id": 368226}} .. _retrieve-aggregate: @@ -164,11 +167,14 @@ purchased color. For more information about how to construct an aggregation pipeline, see the {+mdb-server+} manual page on :manual:`Aggregation `. +Additional Information +---------------------- + API Documentation ------------------ +~~~~~~~~~~~~~~~~~ -For more information on the methods and classes used to retrieve documents -on this page, see the following API Documentation: +For more information about the methods and classes used to retrieve documents +on this page, see the following API cocumentation: - `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ - `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ @@ -176,7 +182,7 @@ on this page, see the following API Documentation: - `aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ Server Manual Entries ---------------------- +~~~~~~~~~~~~~~~~~~~~~ - :manual:`Collections ` - :manual:`Query Documents ` diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 6a6adc42f..5946acb28 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -292,10 +292,10 @@ documents match. ReplaceOne Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following code is a complete, standalone file that performs a replace one operation. - .. include:: /includes/crud/example-intro.rst +The following code is a complete, standalone file that performs a replace one operation. + .. io-code-block:: .. input:: /includes/crud/ReplaceOne.java @@ -311,10 +311,13 @@ The following code is a complete, standalone file that performs a replace one op UpdateMany modified document count: 242 +Additional Information +---------------------- + API Documentation ------------------ +~~~~~~~~~~~~~~~~~ -For more information on the methods and classes used to modify documents, see the following API Documentation: +For more information about the methods and classes used to modify documents, see the following API cocumentation: - `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ - `updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ @@ -323,8 +326,8 @@ For more information on the methods and classes used to modify documents, see th - `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ - `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ -For more information on the methods used in the examples on this -page, see the following API Documentation: +For more information about the methods used in the examples on this +page, see the following API cocumentation: - `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ - `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ @@ -333,7 +336,7 @@ page, see the following API Documentation: - `currentTimestamp() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#currentTimestamp(java.lang.String)>`__ Server Manual Entries ---------------------- +~~~~~~~~~~~~~~~~~~~~~ - :manual:`db.collection.updateOne() ` - :manual:`db.collection.updateMany() ` diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index adf37fdf4..04277854e 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -32,7 +32,7 @@ public static void main(String[] args) { try { // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" DeleteResult result = collection.deleteOne(deleteOneQuery); - System.out.println("DeleteOne document count: " + result.getDeletedCount()); + System.out.println("deleteOne() document count: " + result.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { @@ -46,7 +46,7 @@ public static void main(String[] args) { DeleteResult result = collection.deleteMany(deleteManyQuery); // Prints the number of deleted documents - System.out.println("DeleteMany document count: " + result.getDeletedCount()); + System.out.println("deleteMany() document count: " + result.getDeletedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { diff --git a/source/includes/crud/Find.java b/source/includes/crud/Find.java index 36352f768..fef52f9ba 100644 --- a/source/includes/crud/Find.java +++ b/source/includes/crud/Find.java @@ -48,7 +48,7 @@ public static void main( String[] args ) { if (doc == null) { System.out.println("No results found."); } else { - System.out.println("Document found with find().first()" + doc.toJson()); + System.out.println("Document found with find().first(): " + doc.toJson()); } } } diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index 5c335eac0..68a88b46e 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -34,7 +34,7 @@ public static void main(String[] args) { .append("genres", Arrays.asList("Documentary", "Comedy"))); // Prints the ID of the inserted document - System.out.println("InsertOne document id: " + result.getInsertedId()); + System.out.println("insertOne() document id: " + result.getInsertedId()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { @@ -51,7 +51,7 @@ public static void main(String[] args) { InsertManyResult result = collection.insertMany(movieList); // Prints the IDs of the inserted documents - System.out.println("InsertMany document ids: " + result.getInsertedIds()); + System.out.println("insertMany() document ids: " + result.getInsertedIds()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { From 547f54f255a42f80b7f38419820133f1de4aa7db Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 09:49:14 -0500 Subject: [PATCH 16/27] NR feedback --- source/crud/bulk.txt | 4 ++-- source/crud/delete.txt | 10 +++++----- source/crud/insert.txt | 8 ++++---- source/crud/query-documents/find.txt | 9 ++++----- source/crud/update-documents.txt | 16 ++++++---------- source/includes/crud/Update.java | 4 ++-- 6 files changed, 23 insertions(+), 28 deletions(-) diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 62e950bd3..7826f215b 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -370,7 +370,7 @@ actions: #. Creates a list of instances of the ``InsertOneModel``, ``UpdateOneModel``, ``DeleteOneModel``, and ``ReplaceOneModel`` classes. -#. Runs an ordered ``bulkWrite()`` operation on the list. +#. Runs an ordered ``bulkWrite()`` operation that performs the writes specified in the model list. .. io-code-block:: @@ -640,7 +640,7 @@ MongoCollection - `MongoBulkWriteException <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoBulkWriteException.html>`__ MongoClient -```````````` +``````````` - `bulkWrite() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCluster.html#bulkWrite(com.mongodb.client.ClientSession,java.util.List)>`__ - `ClientBulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/bulk/ClientBulkWriteOptions.html>`__ diff --git a/source/crud/delete.txt b/source/crud/delete.txt index ce5b2fb2d..7b3bde96f 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -154,7 +154,7 @@ Delete Example: Full File .. include:: /includes/crud/example-intro.rst The following code is a complete, standalone file that performs a delete one -operation and a delete many operation. +operation and a delete many operation: .. io-code-block:: @@ -166,11 +166,11 @@ operation and a delete many operation. :language: none :visible: false - DeleteOne document count: 1 - DeleteMany document count: 4 + deleteOne() document count: 1 + deleteMany() document count: 4 -The query in this examples uses the ``eq()`` and ``lt()`` filters to query documents. For more +The queries in these examples use the ``eq()`` and ``lt()`` filters to query documents. For more information about filters, see the `Filters Class <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__ API documentation. @@ -181,7 +181,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For more information about the methods and classes used to delete documents, see the following API cocumentation: +For more information about the methods and classes used to delete documents, see the following API documentation: - `deleteOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson)>`__ - `deleteMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson)>`__ diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 1ff7e3719..fca78e5c6 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -164,7 +164,7 @@ Insert Example: Full File .. include:: /includes/crud/example-intro.rst The following code is a complete, standalone file that performs an insert one -operation and an insert many operation. +operation and an insert many operation: .. io-code-block:: @@ -176,8 +176,8 @@ operation and an insert many operation. :language: none :visible: false - InsertOne document id: BsonObjectId{value=...} - InsertMany document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} + insertOne() document id: BsonObjectId{value=...} + insertMany() document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}} Additional Information ---------------------- @@ -185,7 +185,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For more information about the methods and classes used to insert documents, see the following API cocumentation: +For more information about the methods and classes used to insert documents, see the following API documentation: - `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ - `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 01da8d95c..10e094b80 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -97,11 +97,10 @@ Find Example: Full File .. include:: /includes/crud/example-intro.rst -The following code is a complete, standalone file that performs the following -actions: +This example is a complete, standalone file that performs the following actions: -- Calls the ``find()`` method to retrieve multiple documents that have a ``runtime`` value less than 15, applying a projection and sort to the results -- Calls the ``find()`` and ``first()`` method to retrieve a document that has a ``title`` value of ``"The Room"``, applying a projection and sort before returning the first match +- Calls the ``find()`` method to retrieve multiple documents that have a ``runtime`` value less than ``15``, applying a projection and sort to the results +- Calls the ``find()`` and ``first()`` methods to retrieve a document that has a ``title`` value of ``"The Room"``, applying a projection and sort before returning the first match .. io-code-block:: @@ -174,7 +173,7 @@ API Documentation ~~~~~~~~~~~~~~~~~ For more information about the methods and classes used to retrieve documents -on this page, see the following API cocumentation: +on this page, see the following API documentation: - `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ - `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 5946acb28..67d7efed8 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -175,11 +175,11 @@ documents match. Update Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~ -The following code is a complete, standalone file that performs an update one -operation and an update many operation. - .. include:: /includes/crud/example-intro.rst +The following code is a complete, standalone file that performs an update one +operation and an update many operation: + .. io-code-block:: .. input:: /includes/crud/Update.java @@ -306,10 +306,10 @@ The following code is a complete, standalone file that performs a replace one op :language: none :visible: false - UpdateOne modified document count: 1 + updateOne() modified document count: 1 Upserted ID: null - UpdateMany modified document count: 242 + updateMany() modified document count: 242 Additional Information ---------------------- @@ -317,7 +317,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For more information about the methods and classes used to modify documents, see the following API cocumentation: +For more information about the methods and classes used on this page, see the following API documentation: - `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ - `updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.UpdateOptions)>`__ @@ -325,10 +325,6 @@ For more information about the methods and classes used to modify documents, see - `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ - `ReplaceOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html?is-external=true>`__ - `UpdateResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/UpdateResult.html>`__ - -For more information about the methods used in the examples on this -page, see the following API cocumentation: - - `eq() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html#eq(java.lang.String,TItem)>`__ - `combine() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#combine(org.bson.conversions.Bson...)>`__ - `set() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem)>`__ diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java index 431afe502..fa7a6d12f 100644 --- a/source/includes/crud/Update.java +++ b/source/includes/crud/Update.java @@ -43,7 +43,7 @@ public static void main(String[] args) { UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed - System.out.println("UpdateOne modified document count: " + result.getModifiedCount()); + System.out.println("updateOne() modified document count: " + result.getModifiedCount()); System.out.println("Upserted ID: " + result.getUpsertedId()); // Prints a message if any exceptions occur during the operation @@ -63,7 +63,7 @@ public static void main(String[] args) { UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); // Prints the number of updated documents - System.out.println("\nUpdateMany modified document count: " + result.getModifiedCount()); + System.out.println("\nupdateMany() modified document count: " + result.getModifiedCount()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { From 116ea5ac09a83676cc240f08db5d03724e0f8ad2 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 09:58:29 -0500 Subject: [PATCH 17/27] NR feedback --- source/crud/update-documents.txt | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 67d7efed8..0472d9980 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -190,10 +190,10 @@ operation and an update many operation: :language: none :visible: false - UpdateOne modified document count: 1 + updateOne() modified document count: 1 Upserted ID: null - UpdateMany modified document count: 242 + updateMany() modified document count: 242 .. _replace-operation: @@ -289,8 +289,8 @@ documents match. see :manual:`Unique Indexes ` in the {+mdb-server+} manual. -ReplaceOne Example: Full File -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Replace One Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/crud/example-intro.rst @@ -306,10 +306,8 @@ The following code is a complete, standalone file that performs a replace one op :language: none :visible: false - updateOne() modified document count: 1 - Upserted ID: null - - updateMany() modified document count: 242 + Modified document count: 0 + Upserted id: BsonObjectId{ ... } Additional Information ---------------------- From 31cd656b8cf6a4496cfaac527c6d559b3095bd24 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 12:34:35 -0500 Subject: [PATCH 18/27] comments --- source/includes/crud/BulkWrite.java | 2 +- source/includes/crud/Delete.java | 2 +- source/includes/crud/Find.java | 3 +++ source/includes/crud/Insert.java | 2 +- source/includes/crud/ReplaceOne.java | 2 +- source/includes/crud/Update.java | 2 +- 6 files changed, 8 insertions(+), 5 deletions(-) diff --git a/source/includes/crud/BulkWrite.java b/source/includes/crud/BulkWrite.java index d8cfd4452..d267508a2 100644 --- a/source/includes/crud/BulkWrite.java +++ b/source/includes/crud/BulkWrite.java @@ -1,6 +1,6 @@ // Runs bulk write operations on a collection by using the Java driver -package usage.examples; +package org.example; import java.util.Arrays; diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index 04277854e..4e0b2837a 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -1,6 +1,6 @@ // Deletes a document from a collection by using the Java driver -package usage.examples; +package org.example; import static com.mongodb.client.model.Filters.eq; diff --git a/source/includes/crud/Find.java b/source/includes/crud/Find.java index fef52f9ba..5666e3035 100644 --- a/source/includes/crud/Find.java +++ b/source/includes/crud/Find.java @@ -1,4 +1,7 @@ // Retrieves documents that match a query filter by using the Java driver + +package org.example; + import static com.mongodb.client.model.Filters.lt; import org.bson.Document; diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index 68a88b46e..48f92501b 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -1,6 +1,6 @@ // Inserts a sample document describing a movie by using the Java driver -package usage.examples; +package org.example; import java.util.Arrays; diff --git a/source/includes/crud/ReplaceOne.java b/source/includes/crud/ReplaceOne.java index 8fe84bbef..8c7a83205 100644 --- a/source/includes/crud/ReplaceOne.java +++ b/source/includes/crud/ReplaceOne.java @@ -1,6 +1,6 @@ // Replaces the first document that matches a filter by using the Java driver -package usage.examples; +package org.example; import static com.mongodb.client.model.Filters.eq; diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java index fa7a6d12f..07175e45c 100644 --- a/source/includes/crud/Update.java +++ b/source/includes/crud/Update.java @@ -1,6 +1,6 @@ // Updates the first document that matches a query filter by using the Java driver -package usage.examples; +package org.example; import org.bson.Document; import org.bson.conversions.Bson; From 4af541f0514671dc843a596881897117165be931 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 12:42:42 -0500 Subject: [PATCH 19/27] tags --- source/crud/bulk.txt | 2 +- source/crud/delete.txt | 4 +++- source/crud/insert.txt | 2 ++ source/crud/query-documents/find.txt | 2 ++ source/crud/update-documents.txt | 5 +++++ 5 files changed, 13 insertions(+), 2 deletions(-) diff --git a/source/crud/bulk.txt b/source/crud/bulk.txt index 7826f215b..d0bbdc524 100644 --- a/source/crud/bulk.txt +++ b/source/crud/bulk.txt @@ -1,5 +1,4 @@ .. _java-fundamentals-bulkwrite: -.. _java-usage-bulkwrite: ===================== Bulk Write Operations @@ -359,6 +358,7 @@ see the following API documentation: - `BulkWriteOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html>`__ - `ordered() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/BulkWriteOptions.html#ordered(boolean)>`__ +.. _java-usage-bulkwrite: Bulk Write Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 7b3bde96f..34086b569 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -1,5 +1,4 @@ .. _java-fundamentals-delete: -.. _java-usage-deletemany: ================ Delete Documents @@ -148,6 +147,9 @@ collection: { "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 } +.. _java-usage-deletemany: +.. _java-usage-deleteone: + Delete Example: Full File ------------------------- diff --git a/source/crud/insert.txt b/source/crud/insert.txt index fca78e5c6..c775fbdbc 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -157,6 +157,8 @@ The output of the preceding code resembles the following: Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8] +.. _java-usage-insertmany: +.. _java-usage-insertone: Insert Example: Full File ------------------------- diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 10e094b80..60617a6bb 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -92,6 +92,8 @@ The following shows the output of the preceding query: After the owner runs this query, they find two orders that matched the criteria. +.. _java-usage-find: + Find Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 0472d9980..509ff49fe 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -172,6 +172,9 @@ documents match. see :manual:`Unique Indexes ` in the {+mdb-server+} manual. +.. _java-usage-updatemany: +.. _java-usage-updateone: + Update Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -289,6 +292,8 @@ documents match. see :manual:`Unique Indexes ` in the {+mdb-server+} manual. +.. _java-usage-replaceone: + Replace One Example: Full File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 0c1dba80e139d63ae6a5a2492515b590123c4af8 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 4 Mar 2025 09:34:33 -0500 Subject: [PATCH 20/27] meta data --- source/crud/delete.txt | 8 ++++++++ source/crud/insert.txt | 8 ++++++++ source/crud/query-documents/find.txt | 4 ++-- source/crud/update-documents.txt | 8 ++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/source/crud/delete.txt b/source/crud/delete.txt index 34086b569..bc869f325 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -4,6 +4,14 @@ Delete Documents ================ +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: remove, clear, reset, code example + :description: Learn about how to delete documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none diff --git a/source/crud/insert.txt b/source/crud/insert.txt index c775fbdbc..35102847e 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -4,6 +4,14 @@ Insert Operations ================= +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: add, save, code example + :description: Learn about how to insert documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 60617a6bb..3525478e3 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -9,8 +9,8 @@ Find Documents :values: reference .. meta:: - :keywords: find, findOne, findMany, get, lookup - :description: Learn about how to retrieve data in the {+driver-long+}. + :keywords: find, findOne, findMany, get, lookup, code example + :description: Learn about how to retrieve documents in the {+driver-long+}. .. contents:: On this page :local: diff --git a/source/crud/update-documents.txt b/source/crud/update-documents.txt index 509ff49fe..16d185fd2 100644 --- a/source/crud/update-documents.txt +++ b/source/crud/update-documents.txt @@ -7,6 +7,14 @@ Update Documents ================ +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: update, upsert, correct, change, code example + :description: Learn about how to modify documents in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none From e4999a61e9231186bf8ebba39871b0c6a5c0838c Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 7 Mar 2025 15:38:11 -0500 Subject: [PATCH 21/27] MK feedback --- source/crud/query-documents/find.txt | 22 ++++++++++++++-------- source/includes/crud/Find.java | 25 ++++++++++++++----------- 2 files changed, 28 insertions(+), 19 deletions(-) diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 3525478e3..4395254dd 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -50,9 +50,9 @@ track of the color and quantity, which corresponds to the ``color`` and Find Operation -------------- -Use the find operation to retrieve a subset of your existing data in -MongoDB. You can specify what data to return including which documents -to retrieve, in what order to retrieve them, and how many to retrieve. +Use the find operation to retrieve your documents from MongoDB. You can specify +which documents to retrieve, in what order to retrieve them, and how many to +retrieve. To perform a find operation, call the ``find()`` method on an instance of a ``MongoCollection``. This method searches a collection for documents that @@ -60,9 +60,12 @@ match the query filter you provide. For more information about how to specify a query, see our :ref:`Specify a Query ` guide. -To retrieve a single document, you can append the ``first()`` method to your -``find()`` operation. You can use the ``sort()`` operation before selecting the first -document to help choose the correct file. +To retrieve a single document, you can add the ``first()`` method to your +``find()`` call. To choose a specific document, you can use the ``sort()`` +operation before selecting the first document. You may also want to use the +``limit()`` method to optimize memory usage. For more information, see the +server manual for more information about :manual:`memory optimization when using +the sort operation `. Example ~~~~~~~ @@ -114,9 +117,9 @@ This example is a complete, standalone file that performs the following actions: :language: none :visible: false - Number of documents found with find(): 101 + 10 movies under 15 minutes: 10 Minutes, 3x3, 7:35 in the Morning, 8, 9, A Chairy Tale, A Corner in Wheat, A Gentle Spirit, A Is for Autism, A Movie, - Document found with find().first(): {"title": "The Room", "imdb": {"rating": 3.5, "votes": 25673, "id": 368226}} + The highest rated movie under 15 minutes: {"title": "Andrè and Wally B.", "imdb": {"rating": 5.4, "votes": 3294, "id": 86855}} .. _retrieve-aggregate: @@ -179,6 +182,7 @@ on this page, see the following API documentation: - `find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find()>`__ - `first() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`__ +- `limit() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html#limit(int)>`__ - `FindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ - `aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__ @@ -188,4 +192,6 @@ Server Manual Entries - :manual:`Collections ` - :manual:`Query Documents ` - :manual:`Aggregation ` + - :manual:`$sort ` + - :manual:`$limit ` - :manual:`Aggregation stages ` diff --git a/source/includes/crud/Find.java b/source/includes/crud/Find.java index 5666e3035..0913f3b4e 100644 --- a/source/includes/crud/Find.java +++ b/source/includes/crud/Find.java @@ -27,31 +27,34 @@ public static void main( String[] args ) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - // Creates instructions to project two document fields + // Projects "title" and "imdb" fields, excludes "_id" Bson projectionFields = Projections.fields( Projections.include("title", "imdb"), Projections.excludeId()); - // Retrieves documents that match the filter, applying a projection and a descending sort to the results - MongoCursor cursor = collection.find(lt("runtime", 15)) + // Retrieves documents with a runtime of less than 15 minutes, applying the + // projection and a sorting in alphabetical order + FindIterable docs = collection.find(lt("runtime", 15)) .projection(projectionFields) - .sort(Sorts.descending("title")).iterator(); + .sort(Sorts.ascending("title")) + .limit(10); // Prints the results of the find operation as JSON - System.out.println("Number of documents found with find(): " + cursor.available() + "\n"); - cursor.close(); + System.out.print("10 movies under 15 minutes: "); + docs.forEach(doc -> System.out.print(doc.get("title") + ", ")); - // Retrieves the first matching document, applying a projection and a descending sort to the results - Document doc = collection.find(eq("title", "The Room")) + // Retrieves the document with the best imdb rating that is less + // than 15 minutes long, applying the projection + Document doc = collection.find(lt("runtime", 15)) .projection(projectionFields) - .sort(Sorts.descending("imdb.rating")) + .sort(Sorts.ascending("imdb.rating")) .first(); - // Prints a message if there are no result documents, or prints the result document as JSON + // Prints result document as JSON if (doc == null) { System.out.println("No results found."); } else { - System.out.println("Document found with find().first(): " + doc.toJson()); + System.out.println("\n\nThe highest rated movie under 15 minutes: " + doc.toJson()); } } } From 64420d68afd7b691718f72821d7dd784aba8d0c7 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 7 Mar 2025 15:39:22 -0500 Subject: [PATCH 22/27] MK feedback --- source/includes/crud/Insert.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index 48f92501b..4d34e6d27 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -52,8 +52,6 @@ public static void main(String[] args) { // Prints the IDs of the inserted documents System.out.println("insertMany() document ids: " + result.getInsertedIds()); - - // Prints a message if any exceptions occur during the operation } catch (MongoException me) { System.err.println("Unable to insert due to an error: " + me); } From 272232d9803664932c10bec937ee16634164b9fd Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 11 Mar 2025 21:32:35 -0400 Subject: [PATCH 23/27] MK feedback --- source/crud/delete.txt | 4 ++-- source/crud/query-documents/find.txt | 19 +++++++++++------ source/includes/crud/Delete.java | 32 +++++++++------------------- source/includes/crud/Find.java | 11 +++++----- source/includes/crud/Update.java | 31 ++++++++------------------- 5 files changed, 39 insertions(+), 58 deletions(-) diff --git a/source/crud/delete.txt b/source/crud/delete.txt index bc869f325..1706fa1e6 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -176,8 +176,8 @@ operation and a delete many operation: :language: none :visible: false - deleteOne() document count: 1 - deleteMany() document count: 4 + Deleted document count - query for one: 1 + Deleted document count - unlimited query: 4 The queries in these examples use the ``eq()`` and ``lt()`` filters to query documents. For more diff --git a/source/crud/query-documents/find.txt b/source/crud/query-documents/find.txt index 4395254dd..b86ca6871 100644 --- a/source/crud/query-documents/find.txt +++ b/source/crud/query-documents/find.txt @@ -54,11 +54,13 @@ Use the find operation to retrieve your documents from MongoDB. You can specify which documents to retrieve, in what order to retrieve them, and how many to retrieve. -To perform a find operation, call the ``find()`` method on an instance -of a ``MongoCollection``. This method searches a collection for documents that -match the query filter you provide. For more information about how to -specify a query, see our :ref:`Specify a Query -` guide. +Call the ``find()`` method on an instance of a ``MongoCollection`` to filter for +documents that match the provided query. For more information about how to +specify a query, see our :doc:`Specify a Query ` guide. +You can then use methods such as ``forEach()`` or ``cursor()`` to retrieve +matching documents. For more information, see the `FindIterable +<{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>`__ +API documentation. To retrieve a single document, you can add the ``first()`` method to your ``find()`` call. To choose a specific document, you can use the ``sort()`` @@ -104,8 +106,11 @@ Find Example: Full File This example is a complete, standalone file that performs the following actions: -- Calls the ``find()`` method to retrieve multiple documents that have a ``runtime`` value less than ``15``, applying a projection and sort to the results -- Calls the ``find()`` and ``first()`` methods to retrieve a document that has a ``title`` value of ``"The Room"``, applying a projection and sort before returning the first match +- Calls the ``find()`` method to retrieve 10 documents that has a ``runtime`` + value less than ``15`` minutes, applying a projection and sort to the results +- Calls the ``find()`` and ``first()`` methods to retrieve the document with the + highest ``imdb.rating`` that is has a ``runtime`` value less than ``15`` + minutes, applying a projection to the result .. io-code-block:: diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index 4e0b2837a..a80f6b517 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -1,4 +1,4 @@ -// Deletes a document from a collection by using the Java driver +// Deletes documents from a collection by using the Java driver package org.example; @@ -22,36 +22,24 @@ public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = ""; - try (MongoClient mongoClient = MongoClients.create(uri)) { + try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); Bson deleteOneQuery = eq("title", "The Garbage Pail Kids Movie"); - try { - // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" - DeleteResult result = collection.deleteOne(deleteOneQuery); - System.out.println("deleteOne() document count: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to delete due to an error: " + me); - } + // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" + DeleteResult result = collection.deleteOne(deleteOneQuery); + System.out.println("Deleted document count - query for 1: " + result.getDeletedCount()); Bson deleteManyQuery = lt("imdb.rating", 1.9); - try { - // Deletes all documents that have an "imdb.rating" value less than 1.9 - DeleteResult result = collection.deleteMany(deleteManyQuery); - - // Prints the number of deleted documents - System.out.println("deleteMany() document count: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to delete due to an error: " + me); - } + // Deletes all documents that have an "imdb.rating" value less than 1.9 + result = collection.deleteMany(deleteManyQuery); + + // Prints the number of deleted documents + System.out.println("Deleted document count - unlimited query: " + result.getDeletedCount()); } } } \ No newline at end of file diff --git a/source/includes/crud/Find.java b/source/includes/crud/Find.java index 0913f3b4e..4eeb48a8f 100644 --- a/source/includes/crud/Find.java +++ b/source/includes/crud/Find.java @@ -39,9 +39,10 @@ public static void main( String[] args ) { .sort(Sorts.ascending("title")) .limit(10); - // Prints the results of the find operation as JSON - System.out.print("10 movies under 15 minutes: "); - docs.forEach(doc -> System.out.print(doc.get("title") + ", ")); + // Prints the titles of the queried documents + System.out.println("10 movies under 15 minutes: "); + docs.forEach(doc -> System.out.println("- " + doc.get("title"))); + System.out.println(); // Retrieves the document with the best imdb rating that is less // than 15 minutes long, applying the projection @@ -50,11 +51,11 @@ public static void main( String[] args ) { .sort(Sorts.ascending("imdb.rating")) .first(); - // Prints result document as JSON + // Prints title of the queried document if (doc == null) { System.out.println("No results found."); } else { - System.out.println("\n\nThe highest rated movie under 15 minutes: " + doc.toJson()); + System.out.println("The highest rated movie under 15 minutes: " + doc.toJson().get("title")); } } } diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java index 07175e45c..4652ce6dc 100644 --- a/source/includes/crud/Update.java +++ b/source/includes/crud/Update.java @@ -29,7 +29,6 @@ public static void main(String[] args) { // Instructs the driver to insert a new document if none match the query UpdateOptions options = new UpdateOptions().upsert(true); - Document updateOneQuery = new Document().append("title", "Cool Runnings 2"); // Creates instructions to update the values of three document fields @@ -38,18 +37,12 @@ public static void main(String[] args) { Updates.addToSet("genres", "Sports"), Updates.currentTimestamp("lastUpdated")); - try { - // Updates the first document that has a "title" value of "Cool Runnings 2" - UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); + // Updates the first document that has a "title" value of "Cool Runnings 2" + UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); - // Prints the number of updated documents and the upserted document ID, if an upsert was performed - System.out.println("updateOne() modified document count: " + result.getModifiedCount()); - System.out.println("Upserted ID: " + result.getUpsertedId()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to update due to an error: " + me); - } + // Prints the number of updated documents and the upserted document ID, if an upsert was performed + System.out.println("updateOne() modified document count: " + result.getModifiedCount()); + System.out.println("Upserted ID: " + result.getUpsertedId()); Bson updateManyQuery = gt("num_mflix_comments", 50); @@ -58,17 +51,11 @@ public static void main(String[] args) { Updates.addToSet("genres", "Frequently Discussed"), Updates.currentTimestamp("lastUpdated")); - try { - // Updates documents that have a "num_mflix_comments" value over 50 - UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); - - // Prints the number of updated documents - System.out.println("\nupdateMany() modified document count: " + result.getModifiedCount()); + // Updates documents that have a "num_mflix_comments" value over 50 + UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to update due to an error: " + me); - } + // Prints the number of updated documents + System.out.println("\nupdateMany() modified document count: " + result.getModifiedCount()); } } } From 644972b11bebb3788242525b1ab427c8d97eb337 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 11 Mar 2025 21:47:12 -0400 Subject: [PATCH 24/27] readd --- .../code-snippets/bulk-write/BulkWrite.java | 257 ++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java diff --git a/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java b/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java new file mode 100644 index 000000000..52f806b73 --- /dev/null +++ b/source/includes/fundamentals/code-snippets/bulk-write/BulkWrite.java @@ -0,0 +1,257 @@ +package docs; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.model.ReplaceOneModel; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.DeleteOneModel; +import com.mongodb.client.model.DeleteManyModel; + +import com.mongodb.MongoBulkWriteException; + +import org.bson.Document; + +import java.util.*; + +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import com.mongodb.client.model.WriteModel; + +public class BulkWrite { + + private final MongoCollection collection; + private final MongoClient mongoClient; + private final MongoDatabase database; + + private BulkWrite() { + final String uri = System.getenv("DRIVER_REF_URI"); + + mongoClient = MongoClients.create(uri); + database = mongoClient.getDatabase("crudOps"); + collection = database.getCollection("bulkWrite"); + } + + public static void main(String[] args) { + BulkWrite bulkWrite = new BulkWrite(); + System.out.println("Ordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteExample(); + bulkWrite.preview(); + + System.out.println("Unordered BulkWrite"); + bulkWrite.setUpCollection(); + bulkWrite.bulkWriteNotOrderedExample(); + bulkWrite.preview(); + + System.out.println("Insert BulkWriteException"); + bulkWrite.setUpCollection(); + bulkWrite.insertExceptionExample(); + + System.out.println("Insert"); + bulkWrite.setUpCollection(); + bulkWrite.insertDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Replace"); + bulkWrite.setUpCollection(); + bulkWrite.replaceDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Update"); + bulkWrite.setUpCollection(); + bulkWrite.updateDocumentsExample(); + bulkWrite.preview(); + + System.out.println("Delete"); + bulkWrite.setUpCollection(); + bulkWrite.deleteDocumentsExample(); + bulkWrite.preview(); + } + + + private void insertExceptionExample() { + // begin insertExceptionExample + try { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert documents + InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); + InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); + + bulkOperations.add(doc1); + bulkOperations.add(doc3); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + + // Prints a message if any exceptions occur during the bulk write operation + } catch (MongoBulkWriteException e){ + System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); + } + //end insertExceptionExample + } + + private void bulkWriteNotOrderedExample() { + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // Creates instructions to replace the first document that matches the query + ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), + new Document("name", "Sandy Kane") + .append("location", "Helena, MT")); + + // Creates instructions to update the first document that matches the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents that match the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // begin bulkWriteNotOrderedExample + BulkWriteOptions options = new BulkWriteOptions().ordered(false); + + // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order + collection.bulkWrite(bulkOperations, options); + //end bulkWriteNotOrderedExample + } + + private void bulkWriteExample() { + // begin bulkWriteExample + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert a document + InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) + .append("name", "Zaynab Omar") + .append("age", 37)); + + // 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 first document matched by the query + UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), + Updates.set("name", "Zaynab Hassan")); + + // Creates instructions to delete all documents matched by the query + DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); + + bulkOperations.add(insertDoc); + bulkOperations.add(replaceDoc); + bulkOperations.add(updateDoc); + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order + collection.bulkWrite(bulkOperations); + //end bulkWriteExample + } + + private void insertDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to insert multiple documents + // begin insertDocumentsExample + InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") + .append("age", 17)); + + InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") + .append("age", 22)); + //end insertDocumentsExample + + bulkOperations.add(juneDoc); + bulkOperations.add(kevinDoc); + + // Runs a bulk write operation for the specified insert WriteModels + collection.bulkWrite(bulkOperations); + } + + private void replaceDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to replace the first document matched by the query + // begin replaceDocumentsExample + ReplaceOneModel celineDoc = new ReplaceOneModel<>( + Filters.eq("_id", 1), + new Document("name", "Celine Stork") + .append("location", "San Diego, CA")); + //end replaceDocumentsExample + + bulkOperations.add(celineDoc); + + // Runs a bulk write operation for the specified replace WriteModel + collection.bulkWrite(bulkOperations); + } + + private void updateDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to update the first document matched by the query + // begin updateDocumentsExample + UpdateOneModel updateDoc = new UpdateOneModel<>( + Filters.eq("_id", 2), + Updates.set("age", 31)); + //end updateDocumentsExample + + bulkOperations.add(updateDoc); + + // Runs a bulk write operation for the specified update WriteModel + collection.bulkWrite(bulkOperations); + } + + private void deleteDocumentsExample(){ + List> bulkOperations = new ArrayList<>(); + + // Creates instructions to delete the first document matched by the query + // begin deleteDocumentsExample + DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); + //end deleteDocumentsExample + + bulkOperations.add(deleteDoc); + + // Runs a bulk write operation for the specified delete WriteModel + collection.bulkWrite(bulkOperations); + } + + private void preview(){ + collection.find().forEach(doc -> System.out.println(doc.toJson())); + } + + private void setUpCollection(){ + collection.drop(); + + //begin bulkOpsList + List> bulkOperations = new ArrayList<>(); + //end bulkOpsList + + InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) + .append("name", "Karen Sandoval") + .append("age", 31)); + + InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) + .append("name", "William Chin") + .append("age", 54)); + + InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) + .append("name", "Shayla Ray") + .append("age", 20)); + + bulkOperations.add(karen); + bulkOperations.add(william); + bulkOperations.add(shayla); + + collection.bulkWrite(bulkOperations); + } +} From 967e0df5e4127096767cc9e79b0d9e1fe4a4247b Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 11 Mar 2025 21:48:14 -0400 Subject: [PATCH 25/27] readd --- .../fundamentals/code-snippets/BulkWrite.java | 257 ------------------ 1 file changed, 257 deletions(-) delete mode 100644 source/includes/fundamentals/code-snippets/BulkWrite.java diff --git a/source/includes/fundamentals/code-snippets/BulkWrite.java b/source/includes/fundamentals/code-snippets/BulkWrite.java deleted file mode 100644 index 52f806b73..000000000 --- a/source/includes/fundamentals/code-snippets/BulkWrite.java +++ /dev/null @@ -1,257 +0,0 @@ -package docs; - -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.InsertOneModel; -import com.mongodb.client.model.UpdateOneModel; -import com.mongodb.client.model.ReplaceOneModel; -import com.mongodb.client.model.BulkWriteOptions; -import com.mongodb.client.model.DeleteOneModel; -import com.mongodb.client.model.DeleteManyModel; - -import com.mongodb.MongoBulkWriteException; - -import org.bson.Document; - -import java.util.*; - -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import com.mongodb.client.model.WriteModel; - -public class BulkWrite { - - private final MongoCollection collection; - private final MongoClient mongoClient; - private final MongoDatabase database; - - private BulkWrite() { - final String uri = System.getenv("DRIVER_REF_URI"); - - mongoClient = MongoClients.create(uri); - database = mongoClient.getDatabase("crudOps"); - collection = database.getCollection("bulkWrite"); - } - - public static void main(String[] args) { - BulkWrite bulkWrite = new BulkWrite(); - System.out.println("Ordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteExample(); - bulkWrite.preview(); - - System.out.println("Unordered BulkWrite"); - bulkWrite.setUpCollection(); - bulkWrite.bulkWriteNotOrderedExample(); - bulkWrite.preview(); - - System.out.println("Insert BulkWriteException"); - bulkWrite.setUpCollection(); - bulkWrite.insertExceptionExample(); - - System.out.println("Insert"); - bulkWrite.setUpCollection(); - bulkWrite.insertDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Replace"); - bulkWrite.setUpCollection(); - bulkWrite.replaceDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Update"); - bulkWrite.setUpCollection(); - bulkWrite.updateDocumentsExample(); - bulkWrite.preview(); - - System.out.println("Delete"); - bulkWrite.setUpCollection(); - bulkWrite.deleteDocumentsExample(); - bulkWrite.preview(); - } - - - private void insertExceptionExample() { - // begin insertExceptionExample - try { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert documents - InsertOneModel doc1 = new InsertOneModel<>(new Document("_id", 1)); - InsertOneModel doc3 = new InsertOneModel<>(new Document("_id", 3)); - - bulkOperations.add(doc1); - bulkOperations.add(doc3); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - - // Prints a message if any exceptions occur during the bulk write operation - } catch (MongoBulkWriteException e){ - System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage()); - } - //end insertExceptionExample - } - - private void bulkWriteNotOrderedExample() { - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // Creates instructions to replace the first document that matches the query - ReplaceOneModel replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1), - new Document("name", "Sandy Kane") - .append("location", "Helena, MT")); - - // Creates instructions to update the first document that matches the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents that match the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // begin bulkWriteNotOrderedExample - BulkWriteOptions options = new BulkWriteOptions().ordered(false); - - // Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order - collection.bulkWrite(bulkOperations, options); - //end bulkWriteNotOrderedExample - } - - private void bulkWriteExample() { - // begin bulkWriteExample - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert a document - InsertOneModel insertDoc = new InsertOneModel<>(new Document("_id", 6) - .append("name", "Zaynab Omar") - .append("age", 37)); - - // 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 first document matched by the query - UpdateOneModel updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"), - Updates.set("name", "Zaynab Hassan")); - - // Creates instructions to delete all documents matched by the query - DeleteManyModel deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50)); - - bulkOperations.add(insertDoc); - bulkOperations.add(replaceDoc); - bulkOperations.add(updateDoc); - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order - collection.bulkWrite(bulkOperations); - //end bulkWriteExample - } - - private void insertDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to insert multiple documents - // begin insertDocumentsExample - InsertOneModel juneDoc = new InsertOneModel<>(new Document("name", "June Carrie") - .append("age", 17)); - - InsertOneModel kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss") - .append("age", 22)); - //end insertDocumentsExample - - bulkOperations.add(juneDoc); - bulkOperations.add(kevinDoc); - - // Runs a bulk write operation for the specified insert WriteModels - collection.bulkWrite(bulkOperations); - } - - private void replaceDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to replace the first document matched by the query - // begin replaceDocumentsExample - ReplaceOneModel celineDoc = new ReplaceOneModel<>( - Filters.eq("_id", 1), - new Document("name", "Celine Stork") - .append("location", "San Diego, CA")); - //end replaceDocumentsExample - - bulkOperations.add(celineDoc); - - // Runs a bulk write operation for the specified replace WriteModel - collection.bulkWrite(bulkOperations); - } - - private void updateDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to update the first document matched by the query - // begin updateDocumentsExample - UpdateOneModel updateDoc = new UpdateOneModel<>( - Filters.eq("_id", 2), - Updates.set("age", 31)); - //end updateDocumentsExample - - bulkOperations.add(updateDoc); - - // Runs a bulk write operation for the specified update WriteModel - collection.bulkWrite(bulkOperations); - } - - private void deleteDocumentsExample(){ - List> bulkOperations = new ArrayList<>(); - - // Creates instructions to delete the first document matched by the query - // begin deleteDocumentsExample - DeleteOneModel deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1)); - //end deleteDocumentsExample - - bulkOperations.add(deleteDoc); - - // Runs a bulk write operation for the specified delete WriteModel - collection.bulkWrite(bulkOperations); - } - - private void preview(){ - collection.find().forEach(doc -> System.out.println(doc.toJson())); - } - - private void setUpCollection(){ - collection.drop(); - - //begin bulkOpsList - List> bulkOperations = new ArrayList<>(); - //end bulkOpsList - - InsertOneModel karen = new InsertOneModel<>(new Document("_id", 1) - .append("name", "Karen Sandoval") - .append("age", 31)); - - InsertOneModel william = new InsertOneModel<>(new Document("_id", 2) - .append("name", "William Chin") - .append("age", 54)); - - InsertOneModel shayla = new InsertOneModel<>(new Document("_id", 8) - .append("name", "Shayla Ray") - .append("age", 20)); - - bulkOperations.add(karen); - bulkOperations.add(william); - bulkOperations.add(shayla); - - collection.bulkWrite(bulkOperations); - } -} From c03f77b9867edad6d5fc65e38bed5a1249695c69 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 12 Mar 2025 14:10:40 -0400 Subject: [PATCH 26/27] remove try blocks --- source/includes/crud/BulkWrite.java | 48 +++++++++++++---------------- source/includes/crud/Insert.java | 34 ++++++++------------ 2 files changed, 33 insertions(+), 49 deletions(-) diff --git a/source/includes/crud/BulkWrite.java b/source/includes/crud/BulkWrite.java index d267508a2..bf111b362 100644 --- a/source/includes/crud/BulkWrite.java +++ b/source/includes/crud/BulkWrite.java @@ -27,33 +27,27 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - try { - // Runs a bulk write operation for the specified insert, update, delete, and replace operations - BulkWriteResult result = collection.bulkWrite( - Arrays.asList( - new InsertOneModel<>(new Document("name", "A Sample Movie")), - new InsertOneModel<>(new Document("name", "Another Sample Movie")), - new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new UpdateOneModel<>(new Document("name", "A Sample Movie"), - new Document("$set", new Document("name", "An Old Sample Movie")), - new UpdateOptions().upsert(true)), - - new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), - - new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), - new Document("name", "The Other Sample Movie").append("runtime", "42")) - )); - // Prints the number of inserted, updated, and deleted documents - System.out.println("Result statistics:" + - "\ninserted: " + result.getInsertedCount() + - "\nupdated: " + result.getModifiedCount() + - "\ndeleted: " + result.getDeletedCount()); - - // Prints a message if any exceptions occur during the operations - } catch (MongoException me) { - System.err.println("The bulk write operation failed due to an error: " + me); - } + // Runs a bulk write operation for the specified insert, update, delete, and replace operations + BulkWriteResult result = collection.bulkWrite( + Arrays.asList( + new InsertOneModel<>(new Document("name", "A Sample Movie")), + new InsertOneModel<>(new Document("name", "Another Sample Movie")), + new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new UpdateOneModel<>(new Document("name", "A Sample Movie"), + new Document("$set", new Document("name", "An Old Sample Movie")), + new UpdateOptions().upsert(true)), + + new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), + + new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), + new Document("name", "The Other Sample Movie").append("runtime", "42")) + )); + // Prints the number of inserted, updated, and deleted documents + System.out.println("Result statistics:" + + "\ninserted: " + result.getInsertedCount() + + "\nupdated: " + result.getModifiedCount() + + "\ndeleted: " + result.getDeletedCount()); } } } \ No newline at end of file diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index 4d34e6d27..a4c3ffb06 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -26,35 +26,25 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - try { - // Inserts a sample document describing a movie into the collection - InsertOneResult result = collection.insertOne(new Document() - .append("_id", new ObjectId()) - .append("title", "Ski Bloopers") - .append("genres", Arrays.asList("Documentary", "Comedy"))); - - // Prints the ID of the inserted document - System.out.println("insertOne() document id: " + result.getInsertedId()); - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("Unable to insert due to an error: " + me); - } + // Inserts a sample document describing a movie into the collection + InsertOneResult result = collection.insertOne(new Document() + .append("_id", new ObjectId()) + .append("title", "Ski Bloopers") + .append("genres", Arrays.asList("Documentary", "Comedy"))); + + // Prints the ID of the inserted document + System.out.println("insertOne() document id: " + result.getInsertedId()); // Creates two sample documents containing a "title" field List movieList = Arrays.asList( new Document().append("title", "Short Circuit 3"), new Document().append("title", "The Lego Frozen Movie")); - try { - // Inserts sample documents describing movies into the collection - InsertManyResult result = collection.insertMany(movieList); + // Inserts sample documents describing movies into the collection + InsertManyResult result = collection.insertMany(movieList); - // Prints the IDs of the inserted documents - System.out.println("insertMany() document ids: " + result.getInsertedIds()); - } catch (MongoException me) { - System.err.println("Unable to insert due to an error: " + me); - } + // Prints the IDs of the inserted documents + System.out.println("insertMany() document ids: " + result.getInsertedIds()); } } } From 7028bdd20089e930d9db48dffc3c75348eeab6f1 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Mon, 24 Mar 2025 13:51:23 -0400 Subject: [PATCH 27/27] MK feedback --- source/includes/crud/Delete.java | 4 ++-- source/includes/crud/Insert.java | 4 ++-- source/includes/crud/Update.java | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source/includes/crud/Delete.java b/source/includes/crud/Delete.java index a80f6b517..4658287d0 100644 --- a/source/includes/crud/Delete.java +++ b/source/includes/crud/Delete.java @@ -31,7 +31,7 @@ public static void main(String[] args) { // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" DeleteResult result = collection.deleteOne(deleteOneQuery); - System.out.println("Deleted document count - query for 1: " + result.getDeletedCount()); + System.out.println("Deleted document count - delete one: " + result.getDeletedCount()); Bson deleteManyQuery = lt("imdb.rating", 1.9); @@ -39,7 +39,7 @@ public static void main(String[] args) { result = collection.deleteMany(deleteManyQuery); // Prints the number of deleted documents - System.out.println("Deleted document count - unlimited query: " + result.getDeletedCount()); + System.out.println("Deleted document count - delete many: " + result.getDeletedCount()); } } } \ No newline at end of file diff --git a/source/includes/crud/Insert.java b/source/includes/crud/Insert.java index a4c3ffb06..517e8af58 100644 --- a/source/includes/crud/Insert.java +++ b/source/includes/crud/Insert.java @@ -33,7 +33,7 @@ public static void main(String[] args) { .append("genres", Arrays.asList("Documentary", "Comedy"))); // Prints the ID of the inserted document - System.out.println("insertOne() document id: " + result.getInsertedId()); + System.out.println("Inserted document id - insert one: " + result.getInsertedId()); // Creates two sample documents containing a "title" field List movieList = Arrays.asList( @@ -44,7 +44,7 @@ public static void main(String[] args) { InsertManyResult result = collection.insertMany(movieList); // Prints the IDs of the inserted documents - System.out.println("insertMany() document ids: " + result.getInsertedIds()); + System.out.println("Inserted document id - insert many: " + result.getInsertedIds()); } } } diff --git a/source/includes/crud/Update.java b/source/includes/crud/Update.java index 4652ce6dc..a80b7db4d 100644 --- a/source/includes/crud/Update.java +++ b/source/includes/crud/Update.java @@ -41,8 +41,8 @@ public static void main(String[] args) { UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed - System.out.println("updateOne() modified document count: " + result.getModifiedCount()); - System.out.println("Upserted ID: " + result.getUpsertedId()); + System.out.println("Number of documents updated - update one: " + result.getModifiedCount()); + System.out.println("Upserted document ID: " + result.getUpsertedId()); Bson updateManyQuery = gt("num_mflix_comments", 50); @@ -55,7 +55,7 @@ public static void main(String[] args) { UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates); // Prints the number of updated documents - System.out.println("\nupdateMany() modified document count: " + result.getModifiedCount()); + System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount()); } } }