How to listen for changes to a MongoDB collection?

后端 未结 11 1624
不思量自难忘°
不思量自难忘° 2020-11-22 06:08

I\'m creating a sort of background job queue system with MongoDB as the data store. How can I \"listen\" for inserts to a MongoDB collection before spawning workers to proce

11条回答
  •  一个人的身影
    2020-11-22 06:35

    There is an working java example which can be found here.

     MongoClient mongoClient = new MongoClient();
        DBCollection coll = mongoClient.getDatabase("local").getCollection("oplog.rs");
    
        DBCursor cur = coll.find().sort(BasicDBObjectBuilder.start("$natural", 1).get())
                .addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA);
    
        System.out.println("== open cursor ==");
    
        Runnable task = () -> {
            System.out.println("\tWaiting for events");
            while (cur.hasNext()) {
                DBObject obj = cur.next();
                System.out.println( obj );
    
            }
        };
        new Thread(task).start();
    

    The key is QUERY OPTIONS given here.

    Also you can change find query, if you don't need to load all the data every time.

    BasicDBObject query= new BasicDBObject();
    query.put("ts", new BasicDBObject("$gt", new BsonTimestamp(1471952088, 1))); //timestamp is within some range
    query.put("op", "i"); //Only insert operation
    
    DBCursor cur = coll.find(query).sort(BasicDBObjectBuilder.start("$natural", 1).get())
    .addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA);
    

提交回复
热议问题