How to execute MongoDB query findAndModify in MongoCollection Java driver 3?

The MongoDB 2.5 driver has a DBCollection.findAndModify() method, but MongoCollection skips this method. After some searching, I found that findOneAndUpdate() now has the same role. But this method has a different signature, does not understand how to use it. Here is the command I want to execute

 db.COL1.findAndModify({ query: { id: 2 }, update: { $setOnInsert: { date: new Date(), reptype: 'EOD' } }, new: true, // return new doc if one is upserted upsert: true // insert the document if it does not exist }) 

The documentation for the findOneAndUpdate method claims that

Returns: a document that has been updated. Depending on the value of the returnOriginal property returnOriginal this will either be the document as it was before the update, or as after the update.

but cannot find anything about this property returnOriginal . Does anyone know how to install it correctly?

+5
source share
1 answer

The Java equivalent of your query should look something like this:

 Document query = new Document("id", 2); Document setOnInsert = new Document(); setOnInsert.put("date", new Date()); setOnInsert.put("reptype", "EOD"); Document update = new Document("$setOnInsert", setOnInsert); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.AFTER); options.upsert(true); db.getCollection("COL1").findOneAndUpdate(query, update, options); 

As for the returnOriginal property - you're right - there is no such thing. At this point, javadok doesn't matter. However, in FindOneAndUpdateOptions . You can set it to ReturnDocument.AFTER or ReturnDocument.BEFORE , which is equivalent to new: true/false .

+3
source

Source: https://habr.com/ru/post/1247631/


All Articles