I want to find out if there have been any modifications done to a collection or document in MongoDB

  1. Is there a way to get the last modified time for a collection?
  2. Can we get the last modified time for documents in collection?

Hi @Harinder_Singh1, welcome to the community.
There’s no in-built way(API) that provides the last modified time for a collection or a document.
However, from the top of my head I can think of the following 3 ways to get the last modified time of the collection:

  1. Checkout Auditing which allows administrators to track system activity for deployments with multiple users. Auditing is available on Enterprise Advanced as well as on Atlas(not available for M0 free clusters, M2, and M5 clusters).
  2. You can also utilize Change Streams, which returns a change event notification document, with information on the operation and the changes it made when a change occurs on a watched collection/database.
  3. Create a dedicated collection to track the last modified changes across different collections with the schema that looks something like this:
  collection: <-name of the collection you are tracking->, 
  last_updated: <-update this field every time you update the collection->

To track a document’s last updated time, you can consider adding a new field such as updatedAt which can contain the timestamp of the time it was updated at.
An example document would look like this:

   ...existing fields and values in the document... ,
   updatedAt: ISODate("2022-05-18T14:10:30Z")

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.