diff --git a/source/command.txt b/source/command.txt index 74d0cc50e..a648db05c 100644 --- a/source/command.txt +++ b/source/command.txt @@ -2,7 +2,24 @@ Run a Command ============= -You can run all raw database operations using the +.. 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 + :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 commands include administrative and diagnostic tasks, such as fetching @@ -28,17 +45,16 @@ 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 - :language: java - +.. literalinclude:: /includes/RunCommand.java + :language: java When you run the preceding command, you should see output similar to the following: @@ -50,9 +66,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 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)>`__ + +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..40cd66a08 100644 --- a/source/crud/read-operations.txt +++ b/source/crud/read-operations.txt @@ -11,19 +11,23 @@ Read Operations :caption: Read Operations Retrieve Data - Data from a Cursor + Access Data from a Cursor Sort Results Skip Returned Results Limit Returned Results Specify Fields to Return + Count Documents + Retrieve Distinct Values of a Field 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/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/usage-examples/count.txt b/source/crud/read-operations/count.txt similarity index 75% rename from source/usage-examples/count.txt rename to source/crud/read-operations/count.txt index 90525f1e9..b4c4b24de 100644 --- a/source/usage-examples/count.txt +++ b/source/crud/read-operations/count.txt @@ -1,13 +1,30 @@ -.. _java-usage-count: +.. _java-count: =============== Count Documents =============== +.. facet:: + :name: genre + :values: reference + +.. meta:: + :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 + :local: + :backlinks: none + :depth: 2 + :class: singlecol +Overview +-------- -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 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, @@ -74,17 +91,19 @@ specify the behavior of the call: Both methods return the number of matching documents as a ``long`` primitive. -Example -------- +.. _java-usage-count: + +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/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 @@ -98,10 +117,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 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()>`__ - `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/usage-examples/distinct.txt b/source/crud/read-operations/distinct.txt similarity index 74% rename from source/usage-examples/distinct.txt rename to source/crud/read-operations/distinct.txt index 24c93f6de..39e5829d2 100644 --- a/source/usage-examples/distinct.txt +++ b/source/crud/read-operations/distinct.txt @@ -4,12 +4,28 @@ Retrieve Distinct Values of a Field =================================== +.. facet:: + :name: genre + :values: reference +.. meta:: + :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+}. -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: +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +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 as the second parameter, as shown +below: .. code-block:: java @@ -48,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 @@ -66,7 +82,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/crud/read-operations/geo.txt b/source/crud/read-operations/geo.txt index 346deeefb..6d6d12569 100644 --- a/source/crud/read-operations/geo.txt +++ b/source/crud/read-operations/geo.txt @@ -1,8 +1,16 @@ +.. _java-geo-search: + =================== 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/includes/usage-examples/code-snippets/Command.java b/source/includes/RunCommand.java similarity index 98% rename from source/includes/usage-examples/code-snippets/Command.java rename to source/includes/RunCommand.java index 55ff1cca4..b097525b8 100644 --- a/source/includes/usage-examples/code-snippets/Command.java +++ b/source/includes/RunCommand.java @@ -1,6 +1,6 @@ // 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/includes/usage-examples/code-snippets/CountDocuments.java b/source/includes/crud/CountDocuments.java similarity index 50% rename from source/includes/usage-examples/code-snippets/CountDocuments.java rename to source/includes/crud/CountDocuments.java index badcaf070..9fb22d6a1 100644 --- a/source/includes/usage-examples/code-snippets/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; @@ -24,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/usage-examples/code-snippets/Distinct.java b/source/includes/crud/Distinct.java similarity index 57% rename from source/includes/usage-examples/code-snippets/Distinct.java rename to source/includes/crud/Distinct.java index e90757631..287c15df6 100644 --- a/source/includes/usage-examples/code-snippets/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/includes/usage-examples/code-snippets/Watch.java b/source/includes/crud/Watch.java similarity index 81% rename from source/includes/usage-examples/code-snippets/Watch.java rename to source/includes/crud/Watch.java index 84e119eb7..fe232838e 100644 --- a/source/includes/usage-examples/code-snippets/Watch.java +++ b/source/includes/crud/Watch.java @@ -5,7 +5,7 @@ * to only filter for "insert" and "update" events. */ -package usage.examples; +package org.example; import java.util.Arrays; import java.util.List; @@ -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 ) { @@ -33,21 +34,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/includes/usage-examples/code-snippets/WatchCompanion.java b/source/includes/crud/WatchCompanion.java similarity index 84% rename from source/includes/usage-examples/code-snippets/WatchCompanion.java rename to source/includes/crud/WatchCompanion.java index bdce779c1..2d020c8a0 100644 --- a/source/includes/usage-examples/code-snippets/WatchCompanion.java +++ b/source/includes/crud/WatchCompanion.java @@ -1,12 +1,8 @@ // 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 +10,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 +26,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 +35,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 1d1a10dca..9f245d497 100644 --- a/source/logging-monitoring/change-streams.txt +++ b/source/logging-monitoring/change-streams.txt @@ -1,16 +1,23 @@ .. _java-fundamentals-change-streams: .. _retrieve-watch: +.. _java-usage-watch: =================== Open Change Streams =================== +.. facet:: + :name: genre + :values: reference +.. meta:: + :keywords: watch, changestream, log, monitor, events, code example + :description: Learn about how to use change streams in the {+driver-long+}. .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 3 :class: singlecol Overview @@ -41,6 +48,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``. @@ -51,16 +61,79 @@ 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. + +Filter the Events +~~~~~~~~~~~~~~~~~ + +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 + + List pipeline = List.of( + Aggregates.match( + Filters.in("operationType", + List.of("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: + + .. code-block:: java + + ChangeStreamIterable changeStream = database.watch() + .fullDocument(FullDocument.UPDATE_LOOKUP); + +Manage the Output +~~~~~~~~~~~~~~~~~ + +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 interface, +``MongoIterable`` which implements the core Java interface ``Iterable``. -If you call ``watch()`` on a ``MongoCollection``, the change stream monitors -a collection. +You can call ``forEach()`` on the ``ChangeStreamIterable`` to handle +events as they occur, or you can use the ``iterator()`` method which +returns a ``MongoChangeStreamCursor`` instance that you can use to traverse the results. -If you call ``watch()`` on a ``MongoDatabase``, the change stream monitors all -collections in that database. +You can call the following methods on the ``MongoChangeStreamCursor`: -If you call ``watch()`` on a ``MongoClient``, the change stream monitors all -changes in the connected MongoDB deployment. + - ``hasNext()``: checks if there are more results. + - ``next()`` returns the next document in the collection. + - ``tryNext()`` immediately returns either the next available element in the + change stream or ``null``. + +.. 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 +by ``watch()``. See the link to the ``ChangeStreamIterable`` API +documentation at the bottom of this example for more details on the +available methods. Example ~~~~~~~ @@ -92,7 +165,84 @@ An insert operation on the collection produces the following output: ... } -For a runnable example, see the :ref:`` usage example page. +.. _java-usage-watch: + +Watch Example: Full Files +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +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:: + + The ``Watch.java`` file will continue running until the + ``WatchCompanion.java`` file is run. + +``Watch.java``: + +.. literalinclude:: /includes/crud/Watch.java + :language: java + +``WatchCompanion.java``: + +.. literalinclude:: /includes/crud/WatchCompanion.java + :language: java + +Full File Example Output +```````````````````````` + +The preceding applications will generate the following output: + +``Watch.java`` will capture only the ``insert`` and ``update`` operations, 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 a summary 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 documentation: @@ -172,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:: @@ -342,3 +492,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 +---------------------- + +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()>`__ +- `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 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