java - 数据插入 mongoDB 集合后触发 MongoDB 事件

标签 java angularjs mongodb jsp spring-boot

我对 MongoDB 很陌生。我对 MongoDB 进行了“粗略”的操作。

我想在 MongoDB 中使用事件功能,即数据插入到 MongoDB 集合时应该发生事件,数据应该立即由 MongoDB 本身在 UI 上发出。

这在 MongoDB 中可行吗?

如果是,那么如何?如果不是,那为什么?

提前致谢。

最佳答案

您可以将 tailable cursor 与选项 Bytes.QUERYOPTION_AWAITDATA 一起使用。 Mongodb 的可尾游标文档:https://docs.mongodb.com/manual/core/tailable-cursors/

... After clients insert new additional documents into a capped collection, the tailable cursor will continue to retrieve documents.

当您使用不满足的查询检索文档时,将返回一个空游标。然后,当您调用 cur.hasNext() 时,它将等待数据出现(有超时):

mongoTemplates.createCollection("model", new CollectionOptions(null, 10, true));
DBObject query = new BasicDBObject("value", "val");
DBCursor cur = mongoTemplates.getCollection("model")
            .find(query)
            .addOption(Bytes.QUERYOPTION_TAILABLE)
            .addOption(Bytes.QUERYOPTION_AWAITDATA);

new Thread() {
    public void run() {
        //cur.hasNext will wait for data
        while (cur.hasNext()) {
            DBObject obj = cur.next();
            System.out.println(obj);
        }
    };
}.start();
  • cursor.hasNext() 将在您在 mongodb 中插入以下内容时解除阻塞:db.model.insertOne({value: "val"})

为此,必须使用“capped”选项创建集合:

  • 在 java 中:mongoTemplates.createCollection("model", new CollectionOptions(MAX_SIZE_BYTES, MAX_NB_DOCUMENTS, IS_CAPPED));

  • 在 mongo 客户端中:db.createCollection("model", { capped: true, size: 10 })

Capped Collectiondocumentation 中有解释。 :

By default, MongoDB will automatically close a cursor when the client has exhausted all results in the cursor. However, for capped collections you may use a Tailable Cursor that remains open after the client exhausts the results in the initial cursor.

关于java - 数据插入 mongoDB 集合后触发 MongoDB 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39340821/

相关文章:

java - 为什么 eclipselink/jpa 在我不要求的情况下尝试保留实体?

java - Spark 和 Elastic 导致 jackson 重叠

javascript - 如果失败但使用不同的参数来获取默认数据,则调用相同的 http 请求

node.js - 具有多个条件的聚合和基于计数键的总和匹配

ruby-on-rails - 如何强制轻便摩托车从延迟运行的 Mongo 辅助副本集成员中读取

javaFX-什么是 getBoundsInLocal() 、getBoundsInParent() 方法?

java - 如何确定我的 OpenJDK 库中使用的 xerces 版本?

javascript - 将包含 HTML 标签的字符串传递给指令,标签未呈现

javascript - 返回第一个参数的 Noop 函数

mongodb - 在 MongoDB 中插入时如何检查引用?