David V
David V

Reputation: 11699

Update field only if document updated in MongoDB

I am calling findAndModify() using the $max function to set the value of a field to the largest value.

For example, as shown in the MongoDB documentation.

db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )

I'd like to also set a lastUpdatedTimestamp only if the document is updated. I can't just perform a $set because that will always change the last updated timestamp. Is there a good mechanism within MongoDB to set another value only if the document is updated? Something similar to $setOnInsert but for any update.


If there isn't what might be a good approach here? Right now I'm thinking I could perform a regular find. Then do a local comparison. If the new value is greater than the old, then there is a good possibility that the update will update the document. So I just include the $set for the lastUpdatedTimestamp.

Upvotes: 1

Views: 1434

Answers (2)

HbnKing
HbnKing

Reputation: 1882

as I see you wanted to . update your document only if your highScore can be updated .

only the documents's score is lower than new score value ,it will be updated with score field and lastUpdatedTimestamp

the best way is put your new score in the filter to find the documents match old score < new score

do it like this

db.scores.update(
{_id :4,highScore:{$lt:900}},
{$set:{highScore:900},
$currentDate: { lastModified: true }})

or set the modify time like

{$set:{highScore:900 ,lastupdatetime: new_time},

Upvotes: 1

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

You can first make a query to find records having highScore less than your input value and then update. This will only set lastUpdatedTimestamp on updating the record.

db.scores.findAndModify({
   query: { highScore: { $lt: 950 } },
   update: { $set: { "highScore" : 950, "lastUpdatedTimestamp" : new Date() } },
})

Upvotes: 1

Related Questions