findOne implementation changed while upgrading to mongo-java-driver 3.3.0

mongodb, mongodb-3.3, mongodb-java

Solution

I've found a solution playing around with the implementation in `mongo-java-driver 3.3.0`.

An easy way of performing `findOne` is now as follows -

MongoCollection<CustomDocument> docCollections = mongoClient.getDatabase(dbName).getCollection(collectionName, CustomDocument.class);
CustomDocument firstDocument = docCollections.find(filter).first(); //first for findOne

Problem

We were previously using `mongo-java-driver 3.0.4` , where in a certain block of code has this implementation - ``` DBCollection docCollection = mongoClient.getDB(dbName).getCollection(collectionName); Map<String, Object> docMap = doc.toMap(); // where doc is the CustomDocument DBObject currentObj = docCollection.findOne(new QueryBuilder().put("id").is(doc.getId()).get()); if(currentObj == null) { docCollection.insert(new BasicDBObject(docMap)); } else { docCollection.update(currentObj, new BasicDBObject(docMap)); } ``` What I am trying to achieve now is use `mongo-java-driver 3.3.0` and update the code to get rid of deprecated classes and methods. What I've tried corresponding to the above piece of code is - ``` MongoCollection<CustomDocument> docCollections = mongoClient.getDatabase(dbName).getCollection(collectionName, CustomDocument.class); Bson filter = Filters.eq("id", doc.getId()); // where doc is the CustomDocument FindIterable<Document> documentList = docCollections.find(filter); if (documentList == null) { docCollections.insertOne(doc); } else { docCollections.findOneAndUpdate(filter, new BasicDBObject(docMap)); } ``` What I still find missing is the `findOne` implementation from the collection in my code and the check based actions to be performed for `insert` and `update` accordingly. Any solution/suggestion to this are welcomed.

Original source