Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mongodb

MongoDB 2.5 driver have DBCollection.findAndModify() method for this, but MongoCollection misses this method. After some search, I found that findOneAndUpdate() now has the same role. But this method has different signature, don't understand how to use it. Here is 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
})

Documentation for findOneAndUpdate method states that

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

but cannot find anything about this returnOriginal property. Anyone knows how to set it correctly?

like image 935
Vuk Djapic Avatar asked Apr 21 '16 14:04

Vuk Djapic


1 Answers

A Java equivalent of your query should go roughly 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);

Regarding the returnOriginal property - you're right - there is no such thing. The javadoc is irrelevant in this place. However, there is a returnDocument property in FindOneAndUpdateOptions. You can set it to ReturnDocument.AFTER or ReturnDocument.BEFORE which is equivalent to new: true/false.

like image 188
Lukasz Wiktor Avatar answered Nov 03 '22 21:11

Lukasz Wiktor