13

Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

db.collection.find().limit(1).sort({$natural:-1})

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

void
  • 2,403
  • 6
  • 28
  • 53
  • Remember that the [natural order is not reliable](https://stackoverflow.com/a/33018164/174843), so it's best not to use it at all. – Vince Bowdren May 02 '18 at 12:55

3 Answers3

10

You could get the last insert time same way you mentioned in the question:

db.collection.find().sort({'_id': -1}).limit(1) 

But, There isn't any good way to see the last update/delete time. But, If you are using replica sets you could get that from the oplog.

Or, you could add new field in document as 'lastModified'. You can also checkout collection-hooks. I hope this will help

Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33
5
  1. One way to go about it is to have a field that holds the time of last update. You can name it updatedAt. Every time you make an update to the document, you'll just update the value to the current time. If you use the ISO format to store the time, you'll be able to sort without issues (that's what I use).

  2. The other way is the _id field.

Method 1 db.collection.find().limit(1).sort({updatedAt: -1})

Method 2 db.collection.find().limit(1).sort({_id: -1})

Balocodes
  • 577
  • 7
  • 6
-2

You can try with ,

db.collection.findOne().sort({$natural:-1}).limit(1);
Damini Suthar
  • 1,470
  • 2
  • 14
  • 43