Different keys on two collections of same document for Document Versioning Pattern

Viewed 51

I have a C# application where need to track history of documents, so I want to implement the Document Versioning Pattern. However I'm lost on how to do _id on the hist collection.

Suppose my documents look like this:

{
  _id : "abc",
  rev : 3, 
  loc : "root"
  dat : {
    ..
  }
}

What I tried is two collections, live and hist. But how can I set the _id on the hist table to be on { _id, rev } or a generated ObjectId? Else trying to insert the next rev for "abc" into hist would lead to a duplicate key error.

Attibutes on the c# class won't work as that would lead to the same _id on both collections.

I also thought of putting them into a single collection but that would complicate querying quite a bit if I need all active documents with loc=root.

I'm a bit stumped here and the article doesn't mention this obvious issue.

2 Answers

You do not use _id as _id on history collection. Each history document can have it's own unique _id

Hist

{
  _id: 'own id',  //unique
  ref: '_id of live',
  rev: 3,
  changes: '...'

}

In the end I settled for two properties:

_id 
hid 

When I store in the History table I update the _id field

hid = _id;
_id = $"{_id}_{rev}";

And when I load I switch them back:

_id = hid;
hid = null; 
Related