5
5
* to only filter for "insert" and "update" events.
6
6
*/
7
7
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
+
8
15
package usage .examples ;
9
16
10
17
import java .util .Arrays ;
@@ -26,29 +33,29 @@ public class Watch {
26
33
public static void main ( String [] args ) {
27
34
28
35
// Replace the uri string with your MongoDB deployment's connection string
29
- String uri = "<connection string uri >" ;
36
+ String uri = "<connection string URI >" ;
30
37
31
38
try (MongoClient mongoClient = MongoClients .create (uri )) {
32
39
MongoDatabase database = mongoClient .getDatabase ("sample_mflix" );
33
40
MongoCollection <Document > collection = database .getCollection ("movies" );
34
41
35
42
// Creates instructions to match insert and update operations
36
43
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
+
41
48
// Creates a change stream that receives change events for the specified operations
42
49
ChangeStreamIterable <Document > changeStream = database .watch (pipeline )
43
- .fullDocument (FullDocument .UPDATE_LOOKUP );
44
-
50
+ .fullDocument (FullDocument .UPDATE_LOOKUP );
51
+
45
52
final int [] numberOfEvents = {0 };
46
53
47
54
// Prints a message each time the change stream receives a change event, until it receives two events
48
55
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 );
50
57
if (++numberOfEvents [0 ] >= 2 ) {
51
- System .exit (0 );
58
+ System .exit (0 );
52
59
}
53
60
});
54
61
}
0 commit comments