0

EDIT(15/04/2016): As per the comments received in this question I think there is no direct method in mongodb to do so. In that case is it possible to do this with MongooseJS?


I am using mongodb, For one collection I need an 'lastModified' field, which should show me when in the last time any value of the document actually modified. That means, If I did an update query and all the other values are same, then the 'lastModified' shouldn't get updated.

Example: Suppose I have a document in collection as :

{ _id: 1, status: "a", lastModified: ISODate("2016-04-02T01:11:18.965Z") }

when I update with

{$set:{"status":"a", "lastModified":"Current Time Here"}}

then the "lastModified" should not change

when I update with

{$set:{"status":"b", "lastModified":"Current Time Here"}}

then the "lastModified" should change

How to achieve this?

In my case I will call the update operation multiple times, and I don't want to get the 'lastModified' changed each in this case. Instead it should change only when the 'status' is actually modified.

Ameen Rashad
  • 514
  • 6
  • 17
  • Possibly useful reading: http://stackoverflow.com/questions/9691316/how-to-listen-for-changes-to-a-mongodb-collection – CollinD Apr 13 '16 at 07:22
  • This isn't actually possible in a single update ( without a query ). For example if you just `{ "$set": { "status": "a" } }` then in fact MongoDB is smart enough to not actually change anything if `"status"` is already in fact `"a"`, but it cannot "conditionally" update another field on that premise. The most you can really do is "query" for the value not being the target to set, such as: `.update({ "status": { "$ne": "a" } },{ "$set": { "status": "a", "lastModified": currentTime }})`. And that of course does not even select the document if the property to change is already the same. – Neil Lunn Apr 13 '16 at 07:47
  • What about `$cond:{if: {$eq:["$status", "a"]}, then:"$lastModified", else: "now"}` I'm pretty bad with Updates, so I genuinely have no idea if it might work, also, [check this?](http://stackoverflow.com/questions/2606657/how-can-i-update-field-with-another-fields-value) which might help for the "oldValue" stuff. – Ludovic Migneault Apr 13 '16 at 19:50
  • can this be done with mongoose? – Ameen Rashad Apr 15 '16 at 05:24

0 Answers0