I am very new to MongoDB. I have made a "crude" operation with MongoDB.
I want to work with event functionality in MongoDB which is when data is inserted into MongoDB collection event should occur and data should be imediately emitted on UI by MongoDB itself.
Is This Possible in MongoDB?
If Yes then How? and if No then Why?
Thanks in advance.
You can use a tailable cursor
with the option Bytes.QUERYOPTION_AWAITDATA
. Documentation on Mongodb's tailable cursor: 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.
When you retrieve documents using an unsatisfied query, an empty cursor will be returned. Then, when you call cur.hasNext()
, it will wait for data to be present (with a timeout):
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()
will unblock when you insert the following in mongodb: db.model.insertOne({value: "val"})
For this to work, the collection has to be created with the option "capped":
in java: mongoTemplates.createCollection("model", new CollectionOptions(MAX_SIZE_BYTES, MAX_NB_DOCUMENTS, IS_CAPPED));
in mongo client: db.createCollection( "model", { capped: true, size: 10 } )
The Capped Collection
is explained in the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With