获取mongodb中已更改文档的通知

joe*_*ekr 8 configuration networking mongodb

我正在尝试使用mongodb作为网络范围的配置存储.这个应用程序在网络上的多台机器上运行,每个机器都从其本地mongodb中提取其配置.mongodbs同步.我想要的是在一个应用程序更改任何配置值的情况下在所有n-1个应用程序中获得回调/通知.这种设置可能吗?

(这将使我免于自己进行网络传输/同步等.)

Sid*_*Sid 10

MongoDB还没有触发器,但是您可以挂钩您的应用程序以关闭oplog集合并在每次删除(或更新或插入文档等)文档时执行某些操作

这里的3部分博客文章可能有助于如何做到这一点:http: //www.kchodorow.com/blog/2010/10/12/replication-internals/

  • 这不再是最新的,2017 年的答案应该是公认的。 (2认同)

Dar*_*tar 9

从 mongodb 3.6 开始,您现在可以将操作挂钩到更改流。这为您提供了一个可跟踪的游标,您可以使用它来监听特定集合上的更改(例如 crud 操作)。

变更流建立在 oplog 之上,任何使用 oplog 的人都可以访问。变更流是可恢复的,也可以与聚合操作符一起使用,例如 $match、$project...

更多信息在这里(Java示例):http : //mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/change-streams/

这是来自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();
Run Code Online (Sandbox Code Playgroud)

如果您使用 C#,可以在此处找到示例:

    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);
Run Code Online (Sandbox Code Playgroud)