Search code examples
c#mongodbmongodb-.net-drivernosql

Can I automatically populate LastUpdated fields in MongoDB (using C# driver)


I want to automatically update a LastUpdatedOn field on a mongo document every time a save or update operation occurs on that document.

Rather than putting this burden on every bit of code that does a save/update, is there some way to automatically do this (I'm using the C# driver).

For e.g. in nHibernate you can use interceptors. Is there a similar technique available at either the database or driver level?


Solution

  • interceptors. Is there a similar technique available at either the database or driver level?

    There is no such mechanism in mongodb c# driver and in the mongodb as well. To achieve your needs you can simple wrap all Save, Insert, atomic Update methods and set LastUpdatedOn field there.

    For example you can have base class for your repository, service, whatever where you will wrap your Save methods:

    public abstract class BaseMongoService<T> where T : BaseDocument
    {
       protected abstract MongoCollection Items { get; }
    
       public virtual SafeModeResult Save(T document)
       {
          document.LastUpdatedOn = DateTime.Now;
    
          return Items.Save(document);
       }
       public virtual void Update(IMongoQuery query, IMongoUpdate update)
       {
          update = update.Set("LastUpdatedOn", DateTime.Now);
          Items.Update(query, update);
       }
    }
    

    then you will need inherit all your documents from BaseDocument (or force them implement some interface) to add constraint that all documents should contains LastUpdatedOn field.

    public class BaseDocument
    {
      public DateTime LastUpdatedOn {get;set;}
    }
    

    Then just inherit all data access classes from above one and use Save, Update methods from base class.

    Note: all this code was not tested, it just how i see it can be done.