How to retrieve last update time of each document in MongoDB?

后端 未结 4 895
后悔当初
后悔当初 2021-02-12 12:18

I would like to know if there is a way to get the last update/modify time of data (i.e documents) in a collection in MongoDB. More clearly, I want to make a query to retrieve al

4条回答
  •  抹茶落季
    2021-02-12 13:09

    You can either use an audit trail entity as @user1530669 mentioned (I'm calling mine delta - the code is already available somewhere on StackOverflow).

    Or you can simply save the last change time. I'm generally using a base entity to set that up and all other entities extend it (for your specific requirement you can probably remove the creationDate as the lastChange is enough for you):

    protected Date creationDate;
    protected Date lastChange;
    
    // Getters and setters or final setters which don't do anything,
    // if you only want to allow the entity to update the values
    
    @PrePersist
    public void prePersist() {
        creationDate = (creationDate == null) ? new Date() : creationDate;
        lastChange = (lastChange == null) ? creationDate : new Date();
    }
    

    And in your queries you can then add a filter so that the lastChange attribute is more recent than your retrieval limit.

提交回复
热议问题