55 * to only filter for "insert" and "update" events.
66 */
77
8+ /**
9+ * This file demonstrates how to open a change stream by using the Java driver.
10+ * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens
11+ * to change events in the "movies" collection. The code uses a change stream with a pipeline
12+ * to only filter for "insert" and "update" events.
13+ */
14+
815package usage .examples ;
916
1017import java .util .Arrays ;
@@ -26,29 +33,29 @@ public class Watch {
2633 public static void main ( String [] args ) {
2734
2835 // Replace the uri string with your MongoDB deployment's connection string
29- String uri = "<connection string uri >" ;
36+ String uri = "<connection string URI >" ;
3037
3138 try (MongoClient mongoClient = MongoClients .create (uri )) {
3239 MongoDatabase database = mongoClient .getDatabase ("sample_mflix" );
3340 MongoCollection <Document > collection = database .getCollection ("movies" );
3441
3542 // Creates instructions to match insert and update operations
3643 List <Bson > pipeline = Arrays .asList (
37- Aggregates .match (
38- Filters .in ("operationType" ,
39- Arrays .asList ("insert" , "update" ))));
40-
44+ Aggregates .match (
45+ Filters .in ("operationType" ,
46+ Arrays .asList ("insert" , "update" ))));
47+
4148 // Creates a change stream that receives change events for the specified operations
4249 ChangeStreamIterable <Document > changeStream = database .watch (pipeline )
43- .fullDocument (FullDocument .UPDATE_LOOKUP );
44-
50+ .fullDocument (FullDocument .UPDATE_LOOKUP );
51+
4552 final int [] numberOfEvents = {0 };
4653
4754 // Prints a message each time the change stream receives a change event, until it receives two events
4855 changeStream .forEach (event -> {
49- System .out .println ("Received a change to the collection: " + event );
56+ System .out .println ("Received a change to the collection: " + event );
5057 if (++numberOfEvents [0 ] >= 2 ) {
51- System .exit (0 );
58+ System .exit (0 );
5259 }
5360 });
5461 }
0 commit comments