isNaN1247
isNaN1247

Reputation: 18099

When to create a new document in NoSQL

I've just starting out with NoSQL (in my case CouchDB) and can't seem to answer what I believe should be a simple question, on what the common practice is around creating a new document vs. appending data to an existing one.

I currently have a database per user (meaning that I can give users access ONLY to the data they own).

So at the top level, my CouchDB looks like:

  • UserA_db
  • UserB_db

Say I have a simple notebook application, where each user can have 1 or more notebooks, each containing 1 or more notes.

Is the idea that you add a single document per notebook, like so:

  • UsersA_db
    • NoteBook1_doc = { notes: [ { notebody: 'foo' }, { notebody: 'bar'} ] }
    • NoteBook2_doc = { notes: [ { notebody: 'baz' }, { notebody: 'boo'} ] }

OR, is everything supposed to be completely flat, irrespective of what the document is, what it contains or what it relates to?

  • UsersA_db
    • NoteBook1_doc = { id: 1 }
    • Note1_doc { id: 1, parentBook: 1, notebody: 'foo' }
    • Note2_doc { id: 2, parentBook: 1, notebody: 'bar' }
    • SomethingCompletelyDifferent_doc { id: 1, text: 'all cows eat grass' }
    • AccountInformation_doc { name: 'Bob', age: 34 }

Upvotes: 3

Views: 178

Answers (1)

JasonSmith
JasonSmith

Reputation: 73722

This could go either way, but a useful fact to remember is that documents are the unit of atomic transactions in CouchDB. You an make an atomic, transactional change to data in CouchDB if all the data is within one document.

Also, recall that CouchDB views are called "views" because they let you see your data in various ways, in a completely consistent state. Views always represent a point-in-time snapshot of the data at the time you request them. Views can also collate data together. A view could, for example, show you a notebook by collating together the individual notes.

Joachim is right that this is a judgement call, but personally I would lean more towards your second option: every note is a document.

Upvotes: 2

Related Questions