So I've managed to build up a very basic MongoDB Change Stream in my Spring Boot application:
public class MongoDBChangeStream {
public void changeStream() {
// connect to the local database server
MongoClient mongoClient = MongoClients.create("db uri goes here");
// Select the MongoDB database
MongoDatabase database = mongoClient.getDatabase("MyDatabase");
// Select the collection to query
MongoCollection<Document> collection = database.getCollection("teams");
// Create pipeline for operationType filter
List<Bson> pipeline = Arrays.asList(
Aggregates.match(
Filters.in(
"operationType",
Arrays.asList("insert", "update", "delete")
)));
// Create the Change Stream
ChangeStreamIterable<Document> changeStream = collection.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
// Iterate over the Change Stream
for (ChangeStreamDocument<Document> changeEvent : changeStream) {
// Process the change event here
switch (changeEvent.getOperationType()) {
case INSERT:
System.out.println("MongoDB Change Stream detected an insert");
break;
case UPDATE:
System.out.println("MongoDB Change Stream detected an update");
break;
case DELETE:
System.out.println("MongoDB Change Stream detected a delete");
break;
}
}
}
}
As you can see I'm listening for inserts, updates and deletes in the 'teams' collection, and then just print out the appropriate message in the console.
But how do I actually start the listener? When I run the application, something needs to start the changeStream for it to start watching the collection.. How do I do that?