DEV Community

loading...

How to Track Versions with MongoDB

sonu sharma
Full Stack developer, actively programming in golang, reactJS, typeScript ...
・1 min read

Consider requirement that we have to be able to recreate/query any version of a document that ever existed in a particular collection. So we start out with:

{   docId: "A",
    v: 1,
    color: "red",
    locale: "USA"
}
Enter fullscreen mode Exit fullscreen mode

If we need to set color to “blue”, instead of updating the “color” field from “red” to “blue”, we have to create a new version of the document which now has its full “current” state, and preserve somehow the old version of the document. So we insert

{   docId: "A",
    v: 2,
    color: "blue",
    locale: "USA"
}
Enter fullscreen mode Exit fullscreen mode

The goal is to preserve every state for each object, but we only respond to queries with the “current” or “latest” version, we just have a requirement to be able to have an audit (which would be very infrequent so it’s okay if it’s slow). Is keeping each version as we do in this example the best schema/approach to this problem?

Discussion (0)

Forem Open with the Forem app