简体   繁体   中英

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

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM