I am trying to update a document in Mongo DB using cursor. My Mongo DB Java driver version is 3.3.0. Following is my code snippet.
MongoCollection<Document> collection = mongoDb.getCollection("customer");
MongoCursor<Document> cursor = collection.find().iterator();
try{
while(cursor.hasNext()){
Document oldDoc = cursor.next();
//created new Document newDoc
collection.replaceOne(oldDoc, newDoc);
}
}catch(Exception e){
e.printStackTrace();
}
Though this way, I can update the document, I think this is not the efficient way because here collection is being searched 2 times. I want to update the old document with some values and later on want to save it using some methods like collection.update(oldDoc) or collection.save(oldDoc) without creating a new document. I searched and came across the following post.
Java, MongoDB: How to update every object while iterating a huge collection?
This is exactly what I want, but I don't find save() method in the new API. So I have 3 questions here.
- What is equivalent of save() method in Mongo DB Java driver 3.3.0 API through which I can update or save a document while iterating a cursor?
- Is there anyway by which I can update the existing document without creating a new document in Mongo DB Java driver 3.3.0 API?
- Above link shows save() was part of Mongo DB Java driver API earlier. Any expert answer, why it got dropped from API?