我对 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 Collection
在 documentation 中有解释。 :
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/