Search in sources :

Example 1 with Field

use of com.mongodb.client.model.Field in project mongo-java-driver by mongodb.

the class DocumentationSamples method testWatch.

@Test
public void testWatch() throws InterruptedException {
    assumeTrue(isDiscoverableReplicaSet() && serverVersionAtLeast(3, 6));
    final MongoCollection<Document> inventory = collection;
    final AtomicBoolean stop = new AtomicBoolean(false);
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (!stop.get()) {
                collection.insertMany(asList(new Document("username", "alice"), new Document()));
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                // ignore
                }
                collection.deleteOne(new Document("username", "alice"));
            }
        }
    });
    thread.start();
    // Start Changestream Example 1
    MongoCursor<ChangeStreamDocument<Document>> cursor = inventory.watch().iterator();
    ChangeStreamDocument<Document> next = cursor.next();
    // End Changestream Example 1
    cursor.close();
    // Start Changestream Example 2
    cursor = inventory.watch().fullDocument(FullDocument.UPDATE_LOOKUP).iterator();
    next = cursor.next();
    // End Changestream Example 2
    cursor.close();
    // Start Changestream Example 3
    BsonDocument resumeToken = next.getResumeToken();
    cursor = inventory.watch().resumeAfter(resumeToken).iterator();
    next = cursor.next();
    // End Changestream Example 3
    cursor.close();
    // Start Changestream Example 4
    List<Bson> pipeline = asList(match(Document.parse("{'fullDocument.username': 'alice'}")), addFields(new Field<String>("newField", "this is an added field!")));
    cursor = inventory.watch(pipeline).iterator();
    next = cursor.next();
    // End Changestream Example 4
    cursor.close();
    stop.set(true);
    thread.join();
}
Also used : ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) Document(org.bson.Document) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) FullDocument(com.mongodb.client.model.changestream.FullDocument) BsonDocument(org.bson.BsonDocument) Bson(org.bson.conversions.Bson) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Field(com.mongodb.client.model.Field) BsonDocument(org.bson.BsonDocument) Test(org.junit.Test)

Aggregations

Field (com.mongodb.client.model.Field)1 ChangeStreamDocument (com.mongodb.client.model.changestream.ChangeStreamDocument)1 FullDocument (com.mongodb.client.model.changestream.FullDocument)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 BsonDocument (org.bson.BsonDocument)1 Document (org.bson.Document)1 Bson (org.bson.conversions.Bson)1 Test (org.junit.Test)1