Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Event trigger after data inserted into mongoDB Collection

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.

like image 825
Abhijeet Behare Avatar asked Nov 08 '22 09:11

Abhijeet Behare


1 Answers

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.

like image 169
alexbt Avatar answered Nov 14 '22 22:11

alexbt