public Guid AddDocument(string key, Guid?etag, JObject data, JObject metadata)
        {
            var docPos = Mutator.Documents.FindValue(key);

            EnsureNotLockedByAnotherTransaction(key, Guid.Empty);

            if (docPos == null)
            {
                var max     = Mutator.DocumentsById.GetRightMost();
                var current = max.Type == JTokenType.Null ? 0 : max.Value <int>();
                var docId   = current + 1;
                metadata["@docId"] = new JValue(docId);
                var docKeyPos = Writer.Position;
                BinaryWriter.Write(key);
                Mutator.DocumentsById.Add(docId, docKeyPos);
                Mutator.IncrementDocumentCount();
            }
            else
            {
                var oldEtag = EnsureValidEtag(docPos.Value, etag);
                Mutator.DocumentsByEtag.Remove(oldEtag);
            }
            var  newEtag  = DocumentDatabase.CreateSequentialUuid();
            long position = WriteDocument(key, metadata, newEtag, data);

            Mutator.Documents.Add(key, position);
            Mutator.DocumentsByEtag.Add(newEtag.ToByteArray(), position);
            return(newEtag);
        }