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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With