Java Code Examples for com.mongodb.client.MongoCollection.findOneAndUpdate()

The following are Jave code examples for showing how to use findOneAndUpdate() of the com.mongodb.client.MongoCollection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: polymorphia   File: UpdateTest.java   Source Code and License Vote up 7 votes
@Test
public void updatePojoTest() {

    Bson update = combine(set("user", "Jim"),
            set("action", Action.DELETE),
            // unfortunately at this point we need to provide a non generic class, so the codec is able to determine all types
            // remember: type erasure makes it impossible to retrieve type argument values at runtime
            // @todo provide a mechanism to generate non-generic class on the fly. Is that even possible ?
            // set("listOfPolymorphicTypes", buildNonGenericClassOnTheFly(Arrays.asList(new A(123), new B(456f)), List.class, Type.class),
            set("listOfPolymorphicTypes", new PolymorphicTypeList(Arrays.asList(new A(123), new B(456f)))),
            currentDate("creationDate"),
            currentTimestamp("_id"));

    FindOneAndUpdateOptions findOptions = new FindOneAndUpdateOptions();
    findOptions.upsert(true);
    findOptions.returnDocument(ReturnDocument.AFTER);

    MongoCollection<Pojo> pojoMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Pojo.class);

    Pojo pojo = pojoMongoCollection.findOneAndUpdate(Filters.and(Filters.lt(DBCollection.ID_FIELD_NAME, 0),
            Filters.gt(DBCollection.ID_FIELD_NAME, 0)), update, findOptions);

    assertNotNull(pojo.id);
}