Starting with mongodb 3.6, you can now hook actions into the change stream. This gives you a tail cursor that you can use to listen for changes (e.g. crud operations) in a particular collection.
A stream of changes is created on top of the popup and is accessible to everything that oplog uses. Thread changes are resumed and can also be used with aggregation operators like $ match, $ project ...
More details here (Java example): http://mongodb.imtqy.com/mongo-java-driver/3.6/driver/tutorials/change-streams/
And here is a snippet from https://www.mongodb.com/mongodb-3.6 (Java):
// 1. The database for reactive, real-time applications MongoClient mongoClient; // Create a new MongoClient with a MongoDB URI string. if (args.length == 0) { // Defaults to a localhost replicaset on ports: 27017, 27018, 27019 mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019")); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // Select the MongoDB database. MongoDatabase database = mongoClient.getDatabase("testChangeStreams"); database.drop(); sleep(); // Select the collection to query. MongoCollection<Document> collection = database.getCollection("documents"); // Create the change stream cursor. MongoCursor<Document> cursor = collection.watch().iterator();
If you are working in C #, examples can be found here :
var inventory = database.GetCollection<BsonDocument>("inventory"); var document = new BsonDocument("x", 1); inventory.InsertOne(document); new Thread(() => { Thread.Sleep(TimeSpan.FromMilliseconds(100)); var filter = new BsonDocument("_id", document["_id"]); var update = "{ $set : { x : 2 } }"; inventory.UpdateOne(filter, update); }) .Start();
Darxtar
source share