Reputation: 447
My inserted/updated documents in MongoDb have an auto-updated currentDate, e.g:
> db.TEMP.update({"event" : "sold my iPhone"}, { $currentDate: {lastModified: true}} , {upsert: true} )
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5a6b3799a187fac295097a64")})
It's critical for me to know the value of "lastModified" as soon as I write the object. Since WriteResult returns the newly-inserted object id, I can just fetch the object:
> db.TEMP.findOne({"_id" : ObjectId("5a6b3799a187fac295097a64")})
{
"_id" : ObjectId("5a6b3799a187fac295097a64"),
"event" : "sold my iPhone",
"lastModified" : ISODate("2018-01-26T14:13:45.031Z")
}
But that would mean 2 DB operations (write and read) for each one. Is there a way to have the "WriteResult" contain the lastModified, or just return the newly-inserted/updated object (even the cursor to it)?
Oh, and I'm using a java driver, so I need to be doing this in Java, not in the command line.
Upvotes: 2
Views: 3521
Reputation: 75924
Use findOneAndUpdate
with below FindOneAndUpdateOptions
options.
findOneAndUpdate
by default returns the document before the modification.
Change to below to return whole updated document.
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
options.returnDocument(ReturnDocument.AFTER);
options.upsert(true);
Bson query = Filters.eq("event", "sold my iPhone");
Bson update = Updates.currentDate("lastModified");
collection.findOneAndUpdate(query, update, options);
Include projection in FindOneAndUpdateOptions
to return just lastModified field.
options.projection(Projections.include("lastModified "));
Upvotes: 4
Reputation: 12817
instead of updateOne
change it to findOneAndUpdate
which returns the updated document as well
TDocument findOneAndUpdate(Bson filter, Bson update);
or
TDocument findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options);
Example
Document updatedDoc = collection.findOneAndUpdate(
eq("name", "Café Con Leche"),
combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
System.out.println(updatedDoc);
Log
20:41:44.748 [main] DEBUG org.mongodb.driver.protocol.command - Sending command {findandmodify : BsonString{value='restaurants'}} to database test on connection [connectionId{localValue:2, serverValue:21}] to server 127.0.0.1:27017
20:41:44.764 [main] DEBUG org.mongodb.driver.protocol.command - Command execution completed
Document{{_id=5a6b43d741b7d10d1cb3edb5, name=Café Con Leche, contact=Document{{phone=228-555-9999, [email protected], location=[-73.92502, 40.8279556]}}, stars=1, categories=[Bakery, Coffee, Pastries], lastModified=Fri Jan 26 20:40:34 IST 2018}}
Upvotes: 0