From f224187c1c2cc20e6ef41834e691f593b1b08b4d Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 14:58:53 -0500 Subject: [PATCH 01/19] watch eg --- source/logging-monitoring/change-streams.txt | 23 +++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 1d1a10dca..77f75924c 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -5,8 +5,6 @@ Open Change Streams =================== - - .. contents:: On this page :local: :backlinks: none @@ -92,7 +90,26 @@ An insert operation on the collection produces the following output: ... } -For a runnable example, see the :ref:`` usage example page. +watch() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code is a complete, standalone file that performs an ordered bulk +write operation. + +.. include:: /includes/crud/example-intro.rst + +.. io-code-block:: + + .. input:: /includes/crud/Watch.java + :language: java + :dedent: + + .. output:: + :language: none + :visible: false + + Received a change to the collection: ChangeStreamDocument{ operationType=insert, resumeToken={...}, namespace=sample_mflix.movies, ... } + To learn more about the ``watch()`` method, see the following API documentation: From 7a4bbd1f03cbd76fc54f73a05560d10f35f125c1 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 25 Feb 2025 15:02:10 -0500 Subject: [PATCH 02/19] import aggregates --- source/includes/usage-examples/code-snippets/Watch.java | 1 + 1 file changed, 1 insertion(+) diff --git a/source/includes/usage-examples/code-snippets/Watch.java b/source/includes/usage-examples/code-snippets/Watch.java index 84e119eb7..f6bc82d79 100644 --- a/source/includes/usage-examples/code-snippets/Watch.java +++ b/source/includes/usage-examples/code-snippets/Watch.java @@ -20,6 +20,7 @@ import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.changestream.FullDocument; +import com.mongodb.client.model.Aggregates; public class Watch { public static void main( String[] args ) { From 108ad3fe47f6be220669a3f5b677714cbcbbb379 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 10:14:08 -0500 Subject: [PATCH 03/19] move watch file --- .../code-snippets => crud}/Watch.java | 25 ++++++++++++------- source/logging-monitoring/change-streams.txt | 8 +++--- 2 files changed, 20 insertions(+), 13 deletions(-) rename source/includes/{usage-examples/code-snippets => crud}/Watch.java (71%) diff --git a/source/includes/usage-examples/code-snippets/Watch.java b/source/includes/crud/Watch.java similarity index 71% rename from source/includes/usage-examples/code-snippets/Watch.java rename to source/includes/crud/Watch.java index f6bc82d79..55736371e 100644 --- a/source/includes/usage-examples/code-snippets/Watch.java +++ b/source/includes/crud/Watch.java @@ -5,6 +5,13 @@ * to only filter for "insert" and "update" events. */ +/** + * This file demonstrates how to open a change stream by using the Java driver. + * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens + * to change events in the "movies" collection. The code uses a change stream with a pipeline + * to only filter for "insert" and "update" events. + */ + package usage.examples; import java.util.Arrays; @@ -26,7 +33,7 @@ public class Watch { public static void main( String[] args ) { // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; + String uri = ""; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); @@ -34,21 +41,21 @@ public static void main( String[] args ) { // Creates instructions to match insert and update operations List pipeline = Arrays.asList( - Aggregates.match( - Filters.in("operationType", - Arrays.asList("insert", "update")))); - + Aggregates.match( + Filters.in("operationType", + Arrays.asList("insert", "update")))); + // Creates a change stream that receives change events for the specified operations ChangeStreamIterable changeStream = database.watch(pipeline) - .fullDocument(FullDocument.UPDATE_LOOKUP); - + .fullDocument(FullDocument.UPDATE_LOOKUP); + final int[] numberOfEvents = {0}; // Prints a message each time the change stream receives a change event, until it receives two events changeStream.forEach(event -> { - System.out.println("Received a change to the collection: " + event); + System.out.println("Received a change to the collection: " + event); if (++numberOfEvents[0] >= 2) { - System.exit(0); + System.exit(0); } }); } diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 77f75924c..76ecd215e 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -90,14 +90,14 @@ An insert operation on the collection produces the following output: ... } -watch() Example: Full File -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Watch Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst The following code is a complete, standalone file that performs an ordered bulk write operation. -.. include:: /includes/crud/example-intro.rst - .. io-code-block:: .. input:: /includes/crud/Watch.java From da68352fd9314ee416a4d368d22719c54118f0b0 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 10:55:15 -0500 Subject: [PATCH 04/19] change stream --- source/includes/crud/Watch.java | 13 ------------- source/logging-monitoring/change-streams.txt | 13 +++++++++++-- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/source/includes/crud/Watch.java b/source/includes/crud/Watch.java index 55736371e..818f98ba8 100644 --- a/source/includes/crud/Watch.java +++ b/source/includes/crud/Watch.java @@ -1,16 +1,3 @@ -/** - * This file demonstrates how to open a change stream by using the Java driver. - * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens - * to change events in the "movies" collection. The code uses a change stream with a pipeline - * to only filter for "insert" and "update" events. - */ - -/** - * This file demonstrates how to open a change stream by using the Java driver. - * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens - * to change events in the "movies" collection. The code uses a change stream with a pipeline - * to only filter for "insert" and "update" events. - */ package usage.examples; diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 76ecd215e..a46af15d5 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -95,8 +95,17 @@ Watch Example: Full File .. include:: /includes/crud/example-intro.rst -The following code is a complete, standalone file that performs an ordered bulk -write operation. +This file demonstrates how to open a change stream by using the watch method. +The watch method takes a pipeline as an argument to filter for only ``"insert"`` +and ``"update"`` events. When an insert or update event occurs on the watched +collection, a log of the even is printed to the screen. + +To see output in your terminal: + +#. Run the file in your editor. +#. Insert or update a document in the ``sample_mflix`` database ``movies`` collection. + - You can insert or update documents by using :atlas:`Atlas + ` or :mongosh:`mongosh `. .. io-code-block:: From a96adfd97285f88674b15b65f63f1411546a4d31 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 10:59:41 -0500 Subject: [PATCH 05/19] change stream --- source/logging-monitoring/change-streams.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index a46af15d5..5ae7741db 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -104,7 +104,10 @@ To see output in your terminal: #. Run the file in your editor. #. Insert or update a document in the ``sample_mflix`` database ``movies`` collection. - - You can insert or update documents by using :atlas:`Atlas + +.. tip:: + + You can insert or update documents by using :atlas:`Atlas ` or :mongosh:`mongosh `. .. io-code-block:: From dd30a030f645b533a088ccac50a583c80c3ac8cc Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 13:52:35 -0500 Subject: [PATCH 06/19] link --- source/includes/crud/Watch.java | 3 --- source/logging-monitoring/change-streams.txt | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/source/includes/crud/Watch.java b/source/includes/crud/Watch.java index 818f98ba8..82abf545c 100644 --- a/source/includes/crud/Watch.java +++ b/source/includes/crud/Watch.java @@ -1,6 +1,3 @@ - -package usage.examples; - import java.util.Arrays; import java.util.List; diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 5ae7741db..c225a67d6 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -107,8 +107,7 @@ To see output in your terminal: .. tip:: - You can insert or update documents by using :atlas:`Atlas - ` or :mongosh:`mongosh `. + You can insert or update documents by using :atlas:`Atlas ` or :mongosh:`mongosh `. .. io-code-block:: From 1cdadaf06db1922e06815608584eb7f1fdfcb121 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 15:25:34 -0500 Subject: [PATCH 07/19] change streams --- .../code-snippets => crud}/Command.java | 0 source/includes/crud/Watch.java | 4 +- .../WatchCompanion.java | 17 +- source/logging-monitoring/change-streams.txt | 161 +++++++++++++++--- 4 files changed, 144 insertions(+), 38 deletions(-) rename source/includes/{usage-examples/code-snippets => crud}/Command.java (100%) rename source/includes/{usage-examples/code-snippets => crud}/WatchCompanion.java (82%) diff --git a/source/includes/usage-examples/code-snippets/Command.java b/source/includes/crud/Command.java similarity index 100% rename from source/includes/usage-examples/code-snippets/Command.java rename to source/includes/crud/Command.java diff --git a/source/includes/crud/Watch.java b/source/includes/crud/Watch.java index 82abf545c..ad293fa95 100644 --- a/source/includes/crud/Watch.java +++ b/source/includes/crud/Watch.java @@ -1,3 +1,5 @@ +package org.example; + import java.util.Arrays; import java.util.List; @@ -17,7 +19,7 @@ public class Watch { public static void main( String[] args ) { // Replace the uri string with your MongoDB deployment's connection string - String uri = ""; + String uri = ""; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); diff --git a/source/includes/usage-examples/code-snippets/WatchCompanion.java b/source/includes/crud/WatchCompanion.java similarity index 82% rename from source/includes/usage-examples/code-snippets/WatchCompanion.java rename to source/includes/crud/WatchCompanion.java index bdce779c1..e4b99b4a9 100644 --- a/source/includes/usage-examples/code-snippets/WatchCompanion.java +++ b/source/includes/crud/WatchCompanion.java @@ -1,12 +1,6 @@ -// Performs CRUD operations to generate change events when run with the Watch application - - -package usage.examples; - -import java.util.Arrays; +package org.example; import org.bson.Document; -import org.bson.types.ObjectId; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; @@ -14,6 +8,9 @@ import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.InsertOneResult; +import com.mongodb.client.model.Updates; +import com.mongodb.client.result.UpdateResult; +import com.mongodb.client.result.DeleteResult; public class WatchCompanion { public static void main(String[] args) { @@ -27,7 +24,7 @@ public static void main(String[] args) { try { // Inserts a sample document into the "movies" collection and print its ID InsertOneResult insertResult = collection.insertOne(new Document("test", "sample movie document")); - System.out.println("Success! Inserted document id: " + insertResult.getInsertedId()); + System.out.println("Inserted document id: " + insertResult.getInsertedId()); // Updates the sample document and prints the number of modified documents UpdateResult updateResult = collection.updateOne(new Document("test", "sample movie document"), Updates.set("field2", "sample movie document update")); @@ -36,8 +33,8 @@ public static void main(String[] args) { // Deletes the sample document and prints the number of deleted documents DeleteResult deleteResult = collection.deleteOne(new Document("field2", "sample movie document update")); System.out.println("Deleted " + deleteResult.getDeletedCount() + " document."); - - // Prints a message if any exceptions occur during the operations + + // Prints a message if any exceptions occur during the operations } catch (MongoException me) { System.err.println("Unable to insert, update, or replace due to an error: " + me); } diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index c225a67d6..afa593118 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -8,7 +8,7 @@ Open Change Streams .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -39,6 +39,9 @@ Open a Change Stream You can open a change stream to subscribe to specific types of data changes and produce change events in your application. +Select a Scope to Watch +~~~~~~~~~~~~~~~~~~~~~~~ + To open a change stream, call the ``watch()`` method on an instance of a ``MongoCollection``, ``MongoDatabase``, or ``MongoClient``. @@ -49,16 +52,53 @@ To open a change stream, call the ``watch()`` method on an instance of a see the :ref:`` {+mdb-server+} manual page. The object on which you call the ``watch()`` method on determines the scope of -events that the change stream listens for. +events that the change stream listens for: + +- ``MongoCollection.watch()`` monitors a collection. +- ``MongoDatabase.watch()`` monitors all collections in a database. +- ``MongoClient.watch()`` monitors all changes in the connected MongoDB deployment. -If you call ``watch()`` on a ``MongoCollection``, the change stream monitors -a collection. +Filter the Events +~~~~~~~~~~~~~~~~~ -If you call ``watch()`` on a ``MongoDatabase``, the change stream monitors all -collections in that database. +The ``watch()`` method optionally takes an **aggregation pipeline** which +consists of an array of **stages** as the first parameter to filter and +transform the change event output as follows: + +.. code-block:: java -If you call ``watch()`` on a ``MongoClient``, the change stream monitors all -changes in the connected MongoDB deployment. + List pipeline = Arrays.asList( + Aggregates.match( + Filters.lt("fullDocument.runtime", 15))); + ChangeStreamIterable changeStream = database.watch(pipeline); + +Manage the Output +~~~~~~~~~~~~~~~~~ + +The ``watch()`` method returns an instance of ``ChangeStreamIterable``, a class +that offers several methods to access, organize, and traverse the results. +``ChangeStreamIterable`` also inherits methods from its parent class, +``MongoIterable`` which implements the core Java interface ``Iterable``. + +You can call ``forEach()`` on the ``ChangeStreamIterable`` to handle +events as they occur, or you can use the ``iterator()`` method 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, ``next()`` to return the next document +in the collection, or ``tryNext()``, to immediately return either +the next available element in the change stream or ``null``. Unlike the +``MongoCursor`` returned by other queries, a ``MongoCursor`` associated +with a change stream waits until a change event arrives before +returning a result from ``next()``. As a result, calls to ``next()`` +using a change stream's ``MongoCursor`` never throw a +``java.util.NoSuchElementException``. + +To configure options for processing the documents returned from the change +stream, use member methods of the ``ChangeStreamIterable`` object returned +by ``watch()``. See the link to the ``ChangeStreamIterable`` API +documentation at the bottom of this example for more details on the +available methods. Example ~~~~~~~ @@ -90,36 +130,81 @@ An insert operation on the collection produces the following output: ... } -Watch Example: Full File -~~~~~~~~~~~~~~~~~~~~~~~~ +Watch Example: Full Files +~~~~~~~~~~~~~~~~~~~~~~~~~ .. include:: /includes/crud/example-intro.rst -This file demonstrates how to open a change stream by using the watch method. -The watch method takes a pipeline as an argument to filter for only ``"insert"`` -and ``"update"`` events. When an insert or update event occurs on the watched -collection, a log of the even is printed to the screen. +This example demonstrates how to open a change stream by using the watch method. +The ``Watch.java`` file calls the ``watch()`` method with a pipeline as an +argument to filter for only ``"insert"`` and ``"update"`` events. The +``WatchCompanion.java`` file inserts, updates and deletes a document. + +To use the following examples, run the files in this order: + +#. Run the ``Watch.java`` file. +#. Run the ``WatchCompanion.java`` file. + +.. note:: -To see output in your terminal: + The ``Watch.java`` file will continue running until the ``WatchCompanion.java`` file -#. Run the file in your editor. -#. Insert or update a document in the ``sample_mflix`` database ``movies`` collection. +``Watch.java``: -.. tip:: +.. literalinclude:: /includes/crud/Watch.java + :language: java - You can insert or update documents by using :atlas:`Atlas ` or :mongosh:`mongosh `. +``WatchCompanion.java``: -.. io-code-block:: +.. literalinclude:: /includes/crud/WatchCompanion.java + :language: java - .. input:: /includes/crud/Watch.java - :language: java - :dedent: +Full File Example Output +```````````````````````` - .. output:: - :language: none - :visible: false +The preceding applications will generate the following output: - Received a change to the collection: ChangeStreamDocument{ operationType=insert, resumeToken={...}, namespace=sample_mflix.movies, ... } +``Watch.java`` will capture on the ``insert`` and ``update`` operations are +printed, since the aggregation pipeline filters out the ``delete`` operation: + +.. code-block:: + :copyable: false + + Received a change to the collection: ChangeStreamDocument{ + operationType=OperationType{value='insert'}, + resumeToken={"_data": "825E..."}, + namespace=sample_mflix.movies, + destinationNamespace=null, + fullDocument=Document{{_id=5ec3..., test=sample movie document}}, + documentKey={"_id": {"$oid": "5ec3..."}}, + clusterTime=Timestamp{...}, + updateDescription=null, + txnNumber=null, + lsid=null, + wallTime=BsonDateTime{value=1657...} + } + Received a change to the collection: ChangeStreamDocument{ + operationType=OperationType{value='update'}, + resumeToken={"_data": "825E..."}, + namespace=sample_mflix.movies, + destinationNamespace=null, + fullDocument=Document{{_id=5ec3..., test=sample movie document, field2=sample movie document update}}, + documentKey={"_id": {"$oid": "5ec3..."}}, + clusterTime=Timestamp{...}, + updateDescription=UpdateDescription{removedFields=[], updatedFields={"field2": "sample movie document update"}}, + txnNumber=null, + lsid=null, + wallTime=BsonDateTime{value=1657...} + } + +``WatchCompanion`` will print all of the operations it completed: + +.. code-block:: + :copyable: false + + Inserted document id: BsonObjectId{value=5ec3...} + Updated 1 document. + Deleted 1 document. To learn more about the ``watch()`` method, see the following API @@ -370,3 +455,25 @@ output: For a list of options, see the `FullDocument <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/changestream/FullDocument.html>`__ API documentation. + +Additional Information +---------------------- + +To learn more about the methods and classes used to manage change streams, see the following API documentation: + +API Documentation +~~~~~~~~~~~~~~~~~ + +- `MongoCollection.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#watch()>`__ +- `MongoDatabase.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#watch()>`__ +- `MongoClient.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClient.html#watch()>`__ +- `ChangeStreamIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ChangeStreamIterable.html>`__ +- `MongoCursor <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ + +- :manual:`Change Streams ` +- :manual:`Change Events ` +- :manual:`Aggregation Pipeline ` +- :manual:`Aggregation Stages ` \ No newline at end of file From 66e07494b577035ee24789d49ae5384e48879195 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 26 Feb 2025 16:07:14 -0500 Subject: [PATCH 08/19] cound docs --- .../read-operations}/count.txt | 14 ++++++++++---- .../code-snippets => crud}/CountDocuments.java | 0 source/logging-monitoring/change-streams.txt | 10 ++++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) rename source/{usage-examples => crud/read-operations}/count.txt (91%) rename source/includes/{usage-examples/code-snippets => crud}/CountDocuments.java (100%) diff --git a/source/usage-examples/count.txt b/source/crud/read-operations/count.txt similarity index 91% rename from source/usage-examples/count.txt rename to source/crud/read-operations/count.txt index 90525f1e9..52b802bca 100644 --- a/source/usage-examples/count.txt +++ b/source/crud/read-operations/count.txt @@ -1,13 +1,19 @@ .. _java-usage-count: +.. _java-count: =============== Count Documents =============== +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol - -There are two instance methods in the ``MongoCollection`` class that you can -call to count the number of documents in a collection: +In this guide, you can learn how to count documents in your MongoDB +database collection. There are two instance methods in the ``MongoCollection`` +class that you can call to count the number of documents in a collection: - ``countDocuments()`` returns the number of documents in the collection that match a specified query. If you specify an empty query filter, @@ -84,7 +90,7 @@ collection with ``Canada`` in the ``countries`` field. .. include:: /includes/connect-guide-note.rst -.. literalinclude:: /includes/usage-examples/code-snippets/CountDocuments.java +.. literalinclude:: /includes/crud/CountDocuments.java :language: java If you run the preceding sample code, you should see output that looks something diff --git a/source/includes/usage-examples/code-snippets/CountDocuments.java b/source/includes/crud/CountDocuments.java similarity index 100% rename from source/includes/usage-examples/code-snippets/CountDocuments.java rename to source/includes/crud/CountDocuments.java diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index afa593118..59a1d6400 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -1,14 +1,19 @@ .. _java-fundamentals-change-streams: .. _retrieve-watch: +.. _java-usage-watch: =================== Open Change Streams =================== +.. meta:: + :keywords: watch, changestream, log, monitor, events + :description: Learn about how to use change streams in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none - :depth: 2 + :depth: 3 :class: singlecol Overview @@ -147,7 +152,8 @@ To use the following examples, run the files in this order: .. note:: - The ``Watch.java`` file will continue running until the ``WatchCompanion.java`` file + The ``Watch.java`` file will continue running until the + ``WatchCompanion.java`` file is run. ``Watch.java``: From 92b5f5d91ca9014a028de27aa91092940195bfb3 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 10:10:54 -0500 Subject: [PATCH 09/19] run command --- source/command.txt | 34 +++++++++++++------ source/crud/read-operations.txt | 2 ++ source/crud/read-operations/count.txt | 21 +++++++++--- .../{crud/Command.java => RunCommand.java} | 4 +-- source/logging-monitoring/change-streams.txt | 4 +-- 5 files changed, 45 insertions(+), 20 deletions(-) rename source/includes/{crud/Command.java => RunCommand.java} (94%) diff --git a/source/command.txt b/source/command.txt index 74d0cc50e..60c882558 100644 --- a/source/command.txt +++ b/source/command.txt @@ -2,7 +2,13 @@ Run a Command ============= -You can run all raw database operations using the +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +In this guide, you can learn how to run raw database operations using the ``MongoDatabase.runCommand()`` method. A raw database operation is a command you can execute directly on the {+mdb-server+} CLI. These commands include administrative and diagnostic tasks, such as fetching @@ -28,18 +34,17 @@ By default, ``runCommand`` returns an object of type can specify a return type for ``runCommand()`` as an optional second parameter. -Example -------- +Run Command Example: Full File +------------------------------ In the following sample code, we send the ``dbStats`` command to request statistics from a specific MongoDB database. .. include:: /includes/connect-guide-note.rst -.. literalinclude:: /includes/usage-examples/code-snippets/Command.java +.. literalinclude:: /includes/Command.java :language: java - When you run the preceding command, you should see output similar to the following: @@ -50,9 +55,18 @@ following: .. include:: /includes/legacy-redirect.rst -For additional information on the classes and methods mentioned on this -page, see the following resources: +Additional Information +---------------------- + +API Documentation +~~~~~~~~~~~~~~~~~ + +For additional information on the classes and methods used to run database commands, see the following API documentation: + +- `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ -- `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__ API Documentation -- :manual:`Database Commands ` Server Manual Entry -- :manual:`dbStats ` Server Manual Entry +- :manual:`Database Commands ` +- :manual:`dbStats ` diff --git a/source/crud/read-operations.txt b/source/crud/read-operations.txt index 1c9183ea0..3b29bc828 100644 --- a/source/crud/read-operations.txt +++ b/source/crud/read-operations.txt @@ -16,6 +16,7 @@ Read Operations Skip Returned Results Limit Returned Results Specify Fields to Return + Count Documents Geospatial Data Search Text @@ -25,5 +26,6 @@ Read Operations - :doc:`/crud/read-operations/skip` - :doc:`/crud/read-operations/limit` - :doc:`/crud/read-operations/project` +- :doc:`/crud/read-operations/count` - :doc:`/crud/read-operations/geo` - :doc:`/crud/read-operations/text` diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 52b802bca..184a7eb99 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -8,7 +8,7 @@ Count Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol In this guide, you can learn how to count documents in your MongoDB @@ -80,8 +80,8 @@ specify the behavior of the call: Both methods return the number of matching documents as a ``long`` primitive. -Example -------- +Count Documents Example: Full File +---------------------------------- The following example estimates the number of documents in the ``movies`` collection in the ``sample_mflix`` database, and then returns @@ -104,10 +104,21 @@ like this (exact numbers can vary depending on your data): .. include:: /includes/legacy-redirect.rst -For additional information on the classes and methods mentioned on this -page, see the following API Documentation: +Additional Information +---------------------- + +API Documentation +~~~~~~~~~~~~~~~~~ + +For additional information on the classes and methods used to count documents, see the following API documentation: - `countDocuments() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#countDocuments()>`__ - `estimatedDocumentCount() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#estimatedDocumentCount()>`__ - `CountOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/CountOptions.html>`__ - `EstimatedDocumentCountOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/EstimatedDocumentCountOptions.html>`__ + +Server Manual Entries +~~~~~~~~~~~~~~~~~~~~~ + +- :manual:`db.collection.countDocuments() ` +- :manual:`db.collection.estimatedDocumentCount() ` \ No newline at end of file diff --git a/source/includes/crud/Command.java b/source/includes/RunCommand.java similarity index 94% rename from source/includes/crud/Command.java rename to source/includes/RunCommand.java index 55ff1cca4..05eb89cf4 100644 --- a/source/includes/crud/Command.java +++ b/source/includes/RunCommand.java @@ -1,6 +1,4 @@ -// Runs a database command by using the Java driver - -package usage.examples; +package org.example; import org.bson.BsonDocument; import org.bson.BsonInt64; diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 59a1d6400..fb8807a19 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -465,11 +465,11 @@ API documentation. Additional Information ---------------------- -To learn more about the methods and classes used to manage change streams, see the following API documentation: - API Documentation ~~~~~~~~~~~~~~~~~ +To learn more about the methods and classes used to manage change streams, see the following API documentation: + - `MongoCollection.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#watch()>`__ - `MongoDatabase.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#watch()>`__ - `MongoClient.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClient.html#watch()>`__ From 1fae4d547a14ff6de96a380f498e2bfecf37eda5 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 12:13:19 -0500 Subject: [PATCH 10/19] run command --- source/command.txt | 2 +- source/crud/read-operations/count.txt | 11 ++++++----- source/includes/RunCommand.java | 2 ++ source/includes/crud/CountDocuments.java | 7 ++++++- source/includes/crud/Watch.java | 7 +++++++ source/includes/crud/WatchCompanion.java | 2 ++ 6 files changed, 24 insertions(+), 7 deletions(-) diff --git a/source/command.txt b/source/command.txt index 60c882558..09e715db9 100644 --- a/source/command.txt +++ b/source/command.txt @@ -61,7 +61,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For additional information on the classes and methods used to run database commands, see the following API documentation: +For additional information on the method used to run database commands, see the following API documentation: - `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__ diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 184a7eb99..87614e6f0 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -11,9 +11,10 @@ Count Documents :depth: 2 :class: singlecol -In this guide, you can learn how to count documents in your MongoDB -database collection. There are two instance methods in the ``MongoCollection`` -class that you can call to count the number of documents in a collection: +In this guide, you can learn how to count the number of documents in your +MongoDB database collections. There are two instance methods in the +``MongoCollection`` class that you can call to count the number of documents in +a collection: - ``countDocuments()`` returns the number of documents in the collection that match a specified query. If you specify an empty query filter, @@ -83,13 +84,13 @@ Both methods return the number of matching documents as a ``long`` primitive. Count Documents Example: Full File ---------------------------------- +.. include:: /includes/crud/example-intro.rst + The following example estimates the number of documents in the ``movies`` collection in the ``sample_mflix`` database, and then returns an accurate count of the number of documents in the ``movies`` collection with ``Canada`` in the ``countries`` field. -.. include:: /includes/connect-guide-note.rst - .. literalinclude:: /includes/crud/CountDocuments.java :language: java diff --git a/source/includes/RunCommand.java b/source/includes/RunCommand.java index 05eb89cf4..b097525b8 100644 --- a/source/includes/RunCommand.java +++ b/source/includes/RunCommand.java @@ -1,3 +1,5 @@ +// Runs a database command by using the Java driver + package org.example; import org.bson.BsonDocument; diff --git a/source/includes/crud/CountDocuments.java b/source/includes/crud/CountDocuments.java index badcaf070..6329d1b62 100644 --- a/source/includes/crud/CountDocuments.java +++ b/source/includes/crud/CountDocuments.java @@ -1,4 +1,9 @@ -// Runs count operations on a collection by using the Java driver +/** + * This file demonstrates how to open a change stream by using the Java driver. + * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens + * to change events in the "movies" collection. The code uses a change stream with a pipeline + * to only filter for "insert" and "update" events. + */ package usage.examples; diff --git a/source/includes/crud/Watch.java b/source/includes/crud/Watch.java index ad293fa95..fe232838e 100644 --- a/source/includes/crud/Watch.java +++ b/source/includes/crud/Watch.java @@ -1,3 +1,10 @@ +/** + * This file demonstrates how to open a change stream by using the Java driver. + * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens + * to change events in the "movies" collection. The code uses a change stream with a pipeline + * to only filter for "insert" and "update" events. + */ + package org.example; import java.util.Arrays; diff --git a/source/includes/crud/WatchCompanion.java b/source/includes/crud/WatchCompanion.java index e4b99b4a9..2d020c8a0 100644 --- a/source/includes/crud/WatchCompanion.java +++ b/source/includes/crud/WatchCompanion.java @@ -1,3 +1,5 @@ +// Performs CRUD operations to generate change events when run with the Watch application + package org.example; import org.bson.Document; From 7cbdded2e13c66631e6976db71a298a869d9b70a Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 15:58:00 -0500 Subject: [PATCH 11/19] change stream --- source/command.txt | 8 + source/crud/read-operations.txt | 2 + source/crud/read-operations/count.txt | 8 + .../read-operations}/distinct.txt | 14 +- .../code-snippets => crud}/Distinct.java | 0 source/logging-monitoring/change-streams.txt | 25 +++ source/usage-examples/watch.txt | 188 ------------------ 7 files changed, 56 insertions(+), 189 deletions(-) rename source/{usage-examples => crud/read-operations}/distinct.txt (89%) rename source/includes/{usage-examples/code-snippets => crud}/Distinct.java (100%) delete mode 100644 source/usage-examples/watch.txt diff --git a/source/command.txt b/source/command.txt index 09e715db9..4dc155ce8 100644 --- a/source/command.txt +++ b/source/command.txt @@ -2,6 +2,14 @@ Run a Command ============= +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: database, call, admin, administration, meta, backend, configure + :description: Learn about how to run database commands in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none diff --git a/source/crud/read-operations.txt b/source/crud/read-operations.txt index 3b29bc828..332625178 100644 --- a/source/crud/read-operations.txt +++ b/source/crud/read-operations.txt @@ -17,6 +17,7 @@ Read Operations Limit Returned Results Specify Fields to Return Count Documents + Retrieve Distinct Values of a Field Geospatial Data Search Text @@ -27,5 +28,6 @@ Read Operations - :doc:`/crud/read-operations/limit` - :doc:`/crud/read-operations/project` - :doc:`/crud/read-operations/count` +- :doc:`/crud/read-operations/distinct` - :doc:`/crud/read-operations/geo` - :doc:`/crud/read-operations/text` diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 87614e6f0..82aec3eaa 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -5,6 +5,14 @@ Count Documents =============== +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: count, number, size, collection + :description: Learn about how to count the number of documents in a collection in the {+driver-long+}. + .. contents:: On this page :local: :backlinks: none diff --git a/source/usage-examples/distinct.txt b/source/crud/read-operations/distinct.txt similarity index 89% rename from source/usage-examples/distinct.txt rename to source/crud/read-operations/distinct.txt index 24c93f6de..23dfaa2ae 100644 --- a/source/usage-examples/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -4,7 +4,19 @@ Retrieve Distinct Values of a Field =================================== - +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: find, distinct, unique, discrete + :description: Learn about how to retrieve the number of distinct values of a field in the {+driver-long+}. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol You can retrieve a list of distinct values for a field across a collection by calling the ``distinct()`` method on a ``MongoCollection`` diff --git a/source/includes/usage-examples/code-snippets/Distinct.java b/source/includes/crud/Distinct.java similarity index 100% rename from source/includes/usage-examples/code-snippets/Distinct.java rename to source/includes/crud/Distinct.java diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index fb8807a19..ab45609dd 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -6,6 +6,10 @@ Open Change Streams =================== +.. facet:: + :name: genre + :values: reference + .. meta:: :keywords: watch, changestream, log, monitor, events :description: Learn about how to use change streams in the {+driver-long+}. @@ -73,10 +77,21 @@ transform the change event output as follows: .. code-block:: java List pipeline = Arrays.asList( + Aggregates.match( + Filters.in("operationType", + Arrays.asList("insert", "update"))), Aggregates.match( Filters.lt("fullDocument.runtime", 15))); ChangeStreamIterable changeStream = database.watch(pipeline); +.. note:: + + For update operation change events, change streams only return the modified + fields by default rather than the entire updated document. You can configure + your change stream to also return the most current version of the document + by calling the ``fullDocument()`` member method of the ``ChangeStreamIterable`` + object with the value ``FullDocument.UPDATE_LOOKUP`` as follows: + Manage the Output ~~~~~~~~~~~~~~~~~ @@ -89,6 +104,14 @@ You can call ``forEach()`` on the ``ChangeStreamIterable`` to handle events as they occur, or you can use the ``iterator()`` method which returns a ``MongoCursor`` instance that you can use to traverse the results. +.. important:: forEach() blocks the current thread + + Calls to ``forEach()`` block the current thread as long as the + corresponding change stream listens for events. If your program + needs to continue executing other logic, such as processing requests or + responding to user input, consider creating and listening to your + change stream in a separate thread. + You can call methods on the ``MongoCursor`` such as ``hasNext()`` to check whether additional results exist, ``next()`` to return the next document in the collection, or ``tryNext()``, to immediately return either @@ -135,6 +158,8 @@ An insert operation on the collection produces the following output: ... } +.. _java-usage-watch: + Watch Example: Full Files ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/usage-examples/watch.txt b/source/usage-examples/watch.txt deleted file mode 100644 index 7e0565ff7..000000000 --- a/source/usage-examples/watch.txt +++ /dev/null @@ -1,188 +0,0 @@ -.. _java-usage-watch: - -================= -Watch for Changes -================= - - - -You can keep track of changes to data in MongoDB, such as changes to a -collection, database, or deployment, by opening a **change stream**. A change -stream allows applications to watch for changes to data and react to them. - -The change stream returns **change event** documents when changes occur. A -change event contains information about the updated data. - -Open a change stream by calling the ``watch()`` method on a -``MongoCollection``, ``MongoDatabase``, or ``MongoClient`` object as shown in -the following code example: - -.. code-block:: java - - ChangeStreamIterable changeStream = database.watch(); - -The ``watch()`` method optionally takes an **aggregation pipeline** which -consists of an array of **stages** as the first parameter to filter and -transform the change event output as follows: - -.. code-block:: java - - List pipeline = Arrays.asList( - Aggregates.match( - Filters.lt("fullDocument.runtime", 15))); - ChangeStreamIterable changeStream = database.watch(pipeline); - -The ``watch()`` method returns an instance of ``ChangeStreamIterable``, a class -that offers several methods to access, organize, and traverse the results. -``ChangeStreamIterable`` also inherits methods from its parent class, -``MongoIterable`` which implements the core Java interface ``Iterable``. - -You can call ``forEach()`` on the ``ChangeStreamIterable`` to handle -events as they occur, or you can use the ``iterator()`` method 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, ``next()`` to return the next document -in the collection, or ``tryNext()``, to immediately return either -the next available element in the change stream or ``null``. Unlike the -``MongoCursor`` returned by other queries, a ``MongoCursor`` associated -with a change stream waits until a change event arrives before -returning a result from ``next()``. As a result, calls to ``next()`` -using a change stream's ``MongoCursor`` never throw a -``java.util.NoSuchElementException``. - -To configure options for processing the documents returned from the change -stream, use member methods of the ``ChangeStreamIterable`` object returned -by ``watch()``. See the link to the ``ChangeStreamIterable`` API -documentation at the bottom of this example for more details on the -available methods. - -How to Process Change Stream Events with a Callback ---------------------------------------------------- - -To capture events from a change stream, call the ``forEach()`` method -with a callback function as shown below: - -.. code-block:: java - - changeStream.forEach(event -> System.out.println("Change observed: " + event)); - -The callback function triggers when a change event is emitted. You can -specify logic in the callback to process the event document when it is -received. - -.. important:: forEach() blocks the current thread - - Calls to ``forEach()`` block the current thread as long as the - corresponding change stream listens for events. If your program - needs to continue executing other logic, such as processing requests or - responding to user input, consider creating and listening to your - change stream in a separate thread. - -.. note:: - - For update operation change events, change streams only return the modified - fields by default rather than the entire updated document. You can configure - your change stream to also return the most current version of the document - by calling the ``fullDocument()`` member method of the ``ChangeStreamIterable`` - object with the value ``FullDocument.UPDATE_LOOKUP`` as follows: - - .. code-block:: java - - ChangeStreamIterable changeStream = database.watch() - .fullDocument(FullDocument.UPDATE_LOOKUP); - -Example -------- - -The following example uses two separate applications to demonstrate how -to listen for changes using a change stream: - -- The first application, named ``Watch``, opens a change stream - on the ``movies`` collection in the ``sample_mflix`` database. - ``Watch`` uses an aggregation pipeline to filter changes based on - ``operationType`` so that it only receives insert and update - events (deletes are excluded by omission). ``Watch`` uses a callback - to receive and print the filtered change events that occur on the - collection. - -- The second application, named ``WatchCompanion``, inserts a - single document into the ``movies`` collection in the ``sample_mflix`` - database. Next, ``WatchCompanion`` updates the document with a new - field value. Finally, ``WatchCompanion`` deletes the document. - -First, run ``Watch`` to open the change stream on the collection and -define a callback on the change stream using the ``forEach()`` method. -While ``Watch`` is running, run ``WatchCompanion`` to generate change -events by performing changes to the collection. - -.. include:: /includes/connect-guide-note.rst - -``Watch``: - -.. literalinclude:: /includes/usage-examples/code-snippets/Watch.java - :language: java - -``WatchCompanion``: - -.. literalinclude:: /includes/usage-examples/code-snippets/WatchCompanion.java - :language: java - -If you run the preceding applications in sequence, you should see output from -the ``Watch`` application that is similar to the following. Only the -``insert`` and ``update`` operations are printed, since the aggregation -pipeline filters out the ``delete`` operation: - -.. code-block:: - :copyable: false - - Received a change to the collection: ChangeStreamDocument{ - operationType=OperationType{value='insert'}, - resumeToken={"_data": "825E..."}, - namespace=sample_mflix.movies, - destinationNamespace=null, - fullDocument=Document{{_id=5ec3..., test=sample movie document}}, - documentKey={"_id": {"$oid": "5ec3..."}}, - clusterTime=Timestamp{...}, - updateDescription=null, - txnNumber=null, - lsid=null, - wallTime=BsonDateTime{value=1657...} - } - Received a change to the collection: ChangeStreamDocument{ - operationType=OperationType{value='update'}, - resumeToken={"_data": "825E..."}, - namespace=sample_mflix.movies, - destinationNamespace=null, - fullDocument=Document{{_id=5ec3..., test=sample movie document, field2=sample movie document update}}, - documentKey={"_id": {"$oid": "5ec3..."}}, - clusterTime=Timestamp{...}, - updateDescription=UpdateDescription{removedFields=[], updatedFields={"field2": "sample movie document update"}}, - txnNumber=null, - lsid=null, - wallTime=BsonDateTime{value=1657...} - } - -You should also see output from the ``WatchCompanion`` application that -is similar to the following: - -.. code-block:: - :copyable: false - - Success! Inserted document id: BsonObjectId{value=5ec3...} - Updated 1 document. - Deleted 1 document. - -.. include:: /includes/legacy-redirect.rst - -For additional information on the classes and methods mentioned on this -page, see the following resources: - -- :manual:`Change Streams ` Server Manual Entry -- :manual:`Change Events ` Server Manual Entry -- :manual:`Aggregation Pipeline ` Server Manual Entry -- :manual:`Aggregation Stages ` Server Manual Entry -- `ChangeStreamIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ChangeStreamIterable.html>`__ API Documentation -- `MongoCollection.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#watch()>`__ API Documentation -- `MongoDatabase.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#watch()>`__ API Documentation -- `MongoClient.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClient.html#watch()>`__ API Documentation From 53545a538600b40a89b5871a6da4cb9b69f4d456 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 15:59:58 -0500 Subject: [PATCH 12/19] tag --- source/crud/read-operations/count.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 82aec3eaa..730571eaf 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -1,4 +1,3 @@ -.. _java-usage-count: .. _java-count: =============== @@ -89,6 +88,8 @@ specify the behavior of the call: Both methods return the number of matching documents as a ``long`` primitive. +.. _java-usage-count: + Count Documents Example: Full File ---------------------------------- From 12667818991118dfda1bd2566ec9a31803a85253 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 27 Feb 2025 16:09:57 -0500 Subject: [PATCH 13/19] vale --- source/command.txt | 2 +- source/crud/read-operations/count.txt | 2 +- source/crud/read-operations/distinct.txt | 2 +- source/logging-monitoring/change-streams.txt | 19 +++++++++++-------- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/source/command.txt b/source/command.txt index 4dc155ce8..59e18bce7 100644 --- a/source/command.txt +++ b/source/command.txt @@ -69,7 +69,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For additional information on the method used to run database commands, see the following API documentation: +For more information about the method used to run database commands, see the following API documentation: - `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__ diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 730571eaf..5a6699f58 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -120,7 +120,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -For additional information on the classes and methods used to count documents, see the following API documentation: +For more information about the classes and methods used to count documents, see the following API documentation: - `countDocuments() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#countDocuments()>`__ - `estimatedDocumentCount() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#estimatedDocumentCount()>`__ diff --git a/source/crud/read-operations/distinct.txt b/source/crud/read-operations/distinct.txt index 23dfaa2ae..427407eff 100644 --- a/source/crud/read-operations/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -78,7 +78,7 @@ which resembles the following: .. include:: /includes/legacy-redirect.rst -For additional information on the classes and methods mentioned on this +For more information about the classes and methods mentioned on this page, see the following resources: - `distinct() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#distinct(java.lang.String,java.lang.Class)>`__ API Documentation diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index ab45609dd..f1518dbd1 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -106,17 +106,20 @@ returns a ``MongoCursor`` instance that you can use to traverse the results. .. important:: forEach() blocks the current thread - Calls to ``forEach()`` block the current thread as long as the + Calls to ``forEach()`` block the current thread while the corresponding change stream listens for events. If your program needs to continue executing other logic, such as processing requests or responding to user input, consider creating and listening to your change stream in a separate thread. -You can call methods on the ``MongoCursor`` such as ``hasNext()`` to check -whether additional results exist, ``next()`` to return the next document -in the collection, or ``tryNext()``, to immediately return either -the next available element in the change stream or ``null``. Unlike the -``MongoCursor`` returned by other queries, a ``MongoCursor`` associated +You can call the following methods on the ``MongoCursor`: + + - ``hasNext()``: checks if there are more results. + - ``next()`` returns the next document in the collection. + - ``tryNext()`` immediately returns eitherthe next available element in the + change stream or ``null``. + +Unlike the ``MongoCursor`` returned by other queries, a ``MongoCursor`` associated with a change stream waits until a change event arrives before returning a result from ``next()``. As a result, calls to ``next()`` using a change stream's ``MongoCursor`` never throw a @@ -228,7 +231,7 @@ printed, since the aggregation pipeline filters out the ``delete`` operation: wallTime=BsonDateTime{value=1657...} } -``WatchCompanion`` will print all of the operations it completed: +``WatchCompanion`` will print a summary of the operations it completed: .. code-block:: :copyable: false @@ -493,7 +496,7 @@ Additional Information API Documentation ~~~~~~~~~~~~~~~~~ -To learn more about the methods and classes used to manage change streams, see the following API documentation: +For more information about the methods and classes used to manage change streams, see the following API documentation: - `MongoCollection.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#watch()>`__ - `MongoDatabase.watch() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#watch()>`__ From 4cb32bc46f964fdb8af29d1fb1ae8e004b4b7e2b Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Fri, 28 Feb 2025 13:51:35 -0500 Subject: [PATCH 14/19] RR feedback --- source/command.txt | 7 +++++-- source/crud/read-operations.txt | 22 +++++++++++----------- source/crud/read-operations/count.txt | 3 +++ source/crud/read-operations/distinct.txt | 12 ++++++++---- source/crud/read-operations/geo.txt | 2 ++ 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/source/command.txt b/source/command.txt index 59e18bce7..a648db05c 100644 --- a/source/command.txt +++ b/source/command.txt @@ -16,6 +16,9 @@ Run a Command :depth: 2 :class: singlecol +Overview +-------- + In this guide, you can learn how to run raw database operations using the ``MongoDatabase.runCommand()`` method. A raw database operation is a command you can execute directly on the {+mdb-server+} CLI. These @@ -50,8 +53,8 @@ statistics from a specific MongoDB database. .. include:: /includes/connect-guide-note.rst -.. literalinclude:: /includes/Command.java - :language: java +.. literalinclude:: /includes/RunCommand.java + :language: java When you run the preceding command, you should see output similar to the following: diff --git a/source/crud/read-operations.txt b/source/crud/read-operations.txt index 332625178..40cd66a08 100644 --- a/source/crud/read-operations.txt +++ b/source/crud/read-operations.txt @@ -11,7 +11,7 @@ Read Operations :caption: Read Operations Retrieve Data - Data from a Cursor + Access Data from a Cursor Sort Results Skip Returned Results Limit Returned Results @@ -21,13 +21,13 @@ Read Operations Geospatial Data Search Text -- :doc:`/crud/read-operations/retrieve` -- :doc:`/crud/read-operations/cursor` -- :doc:`/crud/read-operations/sort` -- :doc:`/crud/read-operations/skip` -- :doc:`/crud/read-operations/limit` -- :doc:`/crud/read-operations/project` -- :doc:`/crud/read-operations/count` -- :doc:`/crud/read-operations/distinct` -- :doc:`/crud/read-operations/geo` -- :doc:`/crud/read-operations/text` +- :ref:`Retrieve ` +- :ref:`Access Data From a Cursor ` +- :ref:`Sort Results ` +- :ref:`Skip Returned Results ` +- :ref:`Limit the Number of Returned Results ` +- :ref:`Specify Which Fields to Return ` +- :ref:`Count Documents ` +- :ref:`Retrieve Distinct Values of a Field ` +- :ref:`Search Geospatially ` +- :ref:`Search Text ` diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index 5a6699f58..c1eca3c42 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -18,6 +18,9 @@ Count Documents :depth: 2 :class: singlecol +Overview +-------- + In this guide, you can learn how to count the number of documents in your MongoDB database collections. There are two instance methods in the ``MongoCollection`` class that you can call to count the number of documents in diff --git a/source/crud/read-operations/distinct.txt b/source/crud/read-operations/distinct.txt index 427407eff..86a645492 100644 --- a/source/crud/read-operations/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -18,10 +18,14 @@ Retrieve Distinct Values of a Field :depth: 2 :class: singlecol -You can retrieve a list of distinct values for a field across a -collection by calling the ``distinct()`` method on a ``MongoCollection`` -object. Pass the document field name as the first parameter and the class -you want to cast the results to as the second parameter as shown below: +Overview +-------- + +In this guide, you can learn how to retrieve a list of distinct values for a +field across a collection by calling the ``distinct()`` method on a +``MongoCollection`` object. Pass the document field name as the first parameter +and the class you want to cast the results to as the second parameter as shown +below: .. code-block:: java diff --git a/source/crud/read-operations/geo.txt b/source/crud/read-operations/geo.txt index 346deeefb..e4c27e84c 100644 --- a/source/crud/read-operations/geo.txt +++ b/source/crud/read-operations/geo.txt @@ -1,3 +1,5 @@ +.. _java-geo-search: + =================== Search Geospatially =================== From 890146e1bd3e2c7dba24f5b5b5c37ca8611d8cff Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 4 Mar 2025 09:30:48 -0500 Subject: [PATCH 15/19] RR feedback --- source/crud/read-operations/count.txt | 4 ++-- source/crud/read-operations/distinct.txt | 2 +- source/crud/read-operations/geo.txt | 6 ++++++ source/logging-monitoring/change-streams.txt | 2 +- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/source/crud/read-operations/count.txt b/source/crud/read-operations/count.txt index c1eca3c42..b4c4b24de 100644 --- a/source/crud/read-operations/count.txt +++ b/source/crud/read-operations/count.txt @@ -9,7 +9,7 @@ Count Documents :values: reference .. meta:: - :keywords: count, number, size, collection + :keywords: count, number, size, collection, code example :description: Learn about how to count the number of documents in a collection in the {+driver-long+}. .. contents:: On this page @@ -22,7 +22,7 @@ Overview -------- In this guide, you can learn how to count the number of documents in your -MongoDB database collections. There are two instance methods in the +MongoDB collections. There are two instance methods in the ``MongoCollection`` class that you can call to count the number of documents in a collection: diff --git a/source/crud/read-operations/distinct.txt b/source/crud/read-operations/distinct.txt index 86a645492..fce9c548f 100644 --- a/source/crud/read-operations/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -9,7 +9,7 @@ Retrieve Distinct Values of a Field :values: reference .. meta:: - :keywords: find, distinct, unique, discrete + :keywords: find, distinct, unique, discrete, code example :description: Learn about how to retrieve the number of distinct values of a field in the {+driver-long+}. .. contents:: On this page diff --git a/source/crud/read-operations/geo.txt b/source/crud/read-operations/geo.txt index e4c27e84c..6d6d12569 100644 --- a/source/crud/read-operations/geo.txt +++ b/source/crud/read-operations/geo.txt @@ -4,7 +4,13 @@ Search Geospatially =================== +.. facet:: + :name: genre + :values: reference +.. meta:: + :keywords: find, geo, geographic, location, locale, coordinate, latitude, longitude, code example + :description: Learn about how to search geospatial data in the {+driver-long+}. .. contents:: On this page :local: diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index f1518dbd1..bdeb01890 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -11,7 +11,7 @@ Open Change Streams :values: reference .. meta:: - :keywords: watch, changestream, log, monitor, events + :keywords: watch, changestream, log, monitor, events, code example :description: Learn about how to use change streams in the {+driver-long+}. .. contents:: On this page From 560672c9c45acd72573c1daf99028b47eedeac37 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 12 Mar 2025 10:14:00 -0400 Subject: [PATCH 16/19] JY feedback --- source/crud/read-operations/distinct.txt | 4 +- source/includes/crud/CountDocuments.java | 20 +++----- source/includes/crud/Distinct.java | 20 +++----- source/logging-monitoring/change-streams.txt | 53 +++++++++++--------- 4 files changed, 44 insertions(+), 53 deletions(-) diff --git a/source/crud/read-operations/distinct.txt b/source/crud/read-operations/distinct.txt index fce9c548f..e6e94a223 100644 --- a/source/crud/read-operations/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -24,7 +24,7 @@ Overview In this guide, you can learn how to retrieve a list of distinct values for a field across a collection by calling the ``distinct()`` method on a ``MongoCollection`` object. Pass the document field name as the first parameter -and the class you want to cast the results to as the second parameter as shown +and the class you want to use for the results format as the second parameter as shown below: .. code-block:: java @@ -64,7 +64,7 @@ match movies that include "Carl Franklin" as one of the values in the .. include:: /includes/connect-guide-note.rst -.. literalinclude:: /includes/usage-examples/code-snippets/Distinct.java +.. literalinclude:: /includes/crud/Distinct.java :language: java When you run the example, you should see output that reports each distinct diff --git a/source/includes/crud/CountDocuments.java b/source/includes/crud/CountDocuments.java index 6329d1b62..9fb22d6a1 100644 --- a/source/includes/crud/CountDocuments.java +++ b/source/includes/crud/CountDocuments.java @@ -29,19 +29,13 @@ public static void main(String[] args) { Bson query = eq("countries", "Spain"); - try { - // Retrieves and prints the estimated number of documents in the collection - long estimatedCount = collection.estimatedDocumentCount(); - System.out.println("Estimated number of documents in the movies collection: " + estimatedCount); - - // Retrieves and prints the number of documents with a "countries" value of "Spain" - long matchingCount = collection.countDocuments(query); - System.out.println("Number of movies from Spain: " + matchingCount); - - // Prints a message if any exceptions occur during the operations - } catch (MongoException me) { - System.err.println("An error occurred: " + me); - } + // Retrieves and prints the estimated number of documents in the collection + long estimatedCount = collection.estimatedDocumentCount(); + System.out.println("Estimated number of documents in the movies collection: " + estimatedCount); + + // Retrieves and prints the number of documents with a "countries" value of "Spain" + long matchingCount = collection.countDocuments(query); + System.out.println("Number of movies from Spain: " + matchingCount); } } } \ No newline at end of file diff --git a/source/includes/crud/Distinct.java b/source/includes/crud/Distinct.java index e90757631..287c15df6 100644 --- a/source/includes/crud/Distinct.java +++ b/source/includes/crud/Distinct.java @@ -22,19 +22,13 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection collection = database.getCollection("movies"); - try { - // Retrieves the distinct values of the "year" field present in documents that match the filter - DistinctIterable docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class); - MongoCursor results = docs.iterator(); - - // Prints the distinct "year" values - while(results.hasNext()) { - System.out.println(results.next()); - } - - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { - System.err.println("An error occurred: " + me); + // Retrieves the distinct values of the "year" field present in documents that match the filter + DistinctIterable docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class); + MongoCursor results = docs.iterator(); + + // Prints the distinct "year" values + while(results.hasNext()) { + System.out.println(results.next()); } } } diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index bdeb01890..337a42ca1 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -71,15 +71,15 @@ Filter the Events ~~~~~~~~~~~~~~~~~ The ``watch()`` method optionally takes an **aggregation pipeline** which -consists of an array of **stages** as the first parameter to filter and -transform the change event output as follows: +consists of a list of **stages** as the first parameter, which can be used to +filter and transform the change event output, as follows: .. code-block:: java - List pipeline = Arrays.asList( + List pipeline = List.of( Aggregates.match( Filters.in("operationType", - Arrays.asList("insert", "update"))), + List.of("insert", "update"))), Aggregates.match( Filters.lt("fullDocument.runtime", 15))); ChangeStreamIterable changeStream = database.watch(pipeline); @@ -92,38 +92,42 @@ transform the change event output as follows: by calling the ``fullDocument()`` member method of the ``ChangeStreamIterable`` object with the value ``FullDocument.UPDATE_LOOKUP`` as follows: + .. code-block:: java + + ChangeStreamIterable changeStream = database.watch() + .fullDocument(FullDocument.UPDATE_LOOKUP); + Manage the Output ~~~~~~~~~~~~~~~~~ -The ``watch()`` method returns an instance of ``ChangeStreamIterable``, a class +The ``watch()`` method returns an instance of ``ChangeStreamIterable``, an interface that offers several methods to access, organize, and traverse the results. -``ChangeStreamIterable`` also inherits methods from its parent class, +``ChangeStreamIterable`` also inherits methods from its parent interface, ``MongoIterable`` which implements the core Java interface ``Iterable``. You can call ``forEach()`` on the ``ChangeStreamIterable`` to handle events as they occur, or you can use the ``iterator()`` method which -returns a ``MongoCursor`` instance that you can use to traverse the results. - -.. important:: forEach() blocks the current thread +returns a ``MongoChangeStreamCursor`` instance that you can use to traverse the results. - Calls to ``forEach()`` block the current thread while the - corresponding change stream listens for events. If your program - needs to continue executing other logic, such as processing requests or - responding to user input, consider creating and listening to your - change stream in a separate thread. - -You can call the following methods on the ``MongoCursor`: +You can call the following methods on the ``MongoChangeStreamCursor`: - ``hasNext()``: checks if there are more results. - ``next()`` returns the next document in the collection. - - ``tryNext()`` immediately returns eitherthe next available element in the + - ``tryNext()`` immediately returns either the next available element in the change stream or ``null``. -Unlike the ``MongoCursor`` returned by other queries, a ``MongoCursor`` associated -with a change stream waits until a change event arrives before -returning a result from ``next()``. As a result, calls to ``next()`` -using a change stream's ``MongoCursor`` never throw a -``java.util.NoSuchElementException``. +.. important:: Iterating the Cursor Blocks the Current Thread + + Iterating through a cursor using ``forEach()`` or any ``iterator()`` method + blocks the current thread while the corresponding change stream listens for + events. If your program needs to continue executing other logic, such as + processing requests or responding to user input, consider creating and + listening to your change stream in a separate thread. + +Unlike the ``MongoCursor`` returned by other queries, a +``MongoChangeStreamCursor`` associated with a change stream waits until a change +event arrives before returning a result from ``next()``. As a result, calls to +``next()`` using a change stream's ``MongoChangeStreamCursor`` never throw a ``java.util.NoSuchElementException``. To configure options for processing the documents returned from the change stream, use member methods of the ``ChangeStreamIterable`` object returned @@ -198,8 +202,7 @@ Full File Example Output The preceding applications will generate the following output: -``Watch.java`` will capture on the ``insert`` and ``update`` operations are -printed, since the aggregation pipeline filters out the ``delete`` operation: +``Watch.java`` will capture only the ``insert`` and ``update`` operations, since the aggregation pipeline filters out the ``delete`` operation: .. code-block:: :copyable: false @@ -319,7 +322,7 @@ The following example modifies your change stream by using the .. code-block:: java ChangeStreamIterable changeStream = collection.watch( - Arrays.asList(Document.parse("{ $changeStreamSplitLargeEvent: {} }"))); + List.of(Document.parse("{ $changeStreamSplitLargeEvent: {} }"))); .. note:: From 895a76228e7bb1eb80f6e2b327cefe8b424375e7 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 12 Mar 2025 14:06:08 -0400 Subject: [PATCH 17/19] force rebuild From a3f187e541267ec3f9ea3be8a4fb5dd5fc6ed338 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 18 Mar 2025 10:58:36 -0400 Subject: [PATCH 18/19] JY feedback --- source/crud/read-operations/distinct.txt | 2 +- source/logging-monitoring/change-streams.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/source/crud/read-operations/distinct.txt b/source/crud/read-operations/distinct.txt index e6e94a223..39e5829d2 100644 --- a/source/crud/read-operations/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -24,7 +24,7 @@ Overview In this guide, you can learn how to retrieve a list of distinct values for a field across a collection by calling the ``distinct()`` method on a ``MongoCollection`` object. Pass the document field name as the first parameter -and the class you want to use for the results format as the second parameter as shown +and the class you want to use for the results as the second parameter, as shown below: .. code-block:: java diff --git a/source/logging-monitoring/change-streams.txt b/source/logging-monitoring/change-streams.txt index 337a42ca1..9f245d497 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -70,9 +70,9 @@ events that the change stream listens for: Filter the Events ~~~~~~~~~~~~~~~~~ -The ``watch()`` method optionally takes an **aggregation pipeline** which -consists of a list of **stages** as the first parameter, which can be used to -filter and transform the change event output, as follows: +The ``watch()`` method takes an optional **aggregation pipeline** as the first +parameter, which consists of a list of **stages** that can be used to +filter and transform the change event output, as follows: .. code-block:: java From 85202743df0fa4aada8f96e4443990cb4c53c35f Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 18 Mar 2025 13:20:45 -0400 Subject: [PATCH 19/19] force rebuild