sql >> Base de Datos >  >> NoSQL >> MongoDB

Reciba notificaciones de documentos modificados en mongodb

A partir de mongodb 3.6, ahora puede vincular acciones al flujo de cambios. Esto le brinda un cursor rastreable que puede usar para escuchar los cambios (por ejemplo, operaciones crudas) en una colección en particular.

El flujo de cambios se construye sobre el oplog y es accesible para cualquier persona que esté usando el oplog. Los flujos de cambios son reanudables y también se pueden usar con operadores de agregación como $coincidencia, $proyecto...

Más información aquí (ejemplo de Java):http://mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/change-streams/

Y aquí está el fragmento de 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();

Si está trabajando en C#, puede encontrar ejemplos aquí:

    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();

    // Start Changestream Example 2
    var options = new ChangeStreamOptions { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
    var enumerator = inventory.Watch(options).ToEnumerable().GetEnumerator();
    enumerator.MoveNext();
    var next = enumerator.Current;
    enumerator.Dispose();
    // End Changestream Example 2

    var expectedFullDocument = document.Set("x", 2);
    next.FullDocument.Should().Be(expectedFullDocument);