Recently I'm exploring NoSQL Databases. I need an advice about how to store data in the most optimal and efficient way for a given problem. I'm targeting MongoDB, now. However it should be the same with CouchDB.
Let's say we have these 3 Models:
Story:
id
title
User:
id
name
Vote:
id
story_id
user_id
I want to be able to ask the database these questions:
I'm doing simple joins while working with a relational DB. The question is, how should I store the data for those objects in order to be most efficient.
For example, if I store the Vote objects as a subcollection of Stories it wont be easy to get the info - "What a user has voted for".
MongoDB is a database based on a non-relational document model. Thus, as a so-called NoSQL database (NoSQL = Not-only-SQL), it differs fundamentally from conventional relational databases such as Oracle, MySQL or the Microsoft SQL Server.
The biggest difference between NoSQL systems lies in the ability to query data efficiently. Document databases provide the richest query functionality, which allows them to address a wide variety of applications. Key-value stores and wide column stores provide a single means of accessing data: by primary key.
NoSQL databases provide a variety of data models such as key-value, document, and graph, which are optimized for performance and scale. Relational databases provide atomicity, consistency, isolation, and durability (ACID) properties: Atomicity requires a transaction to execute completely or not at all.
MongoDB provides two types of data models: — Embedded data model and Normalized data model.
I would suggest storing votes as a list of story _id
s in each user. That way you can find out what stories a user has voted for just by looking at the list. To get the users who have voted for a story you can do something like:
db.users.find({stories: story_id})
where story_id
is the _id
of the story in question. If you create an index on the stories
field both of those queries will be fast.
The way I have been going about the mind switch is to forget about the database alltogether. In the relational db world you always have to worry about data normalization and your table structure. Ditch it all. Just layout your web page. Lay them all out. Now look at them. Your already 2/3 there. If you forget the notion that database size matters and data shouldn't be duplicated than your 3/4 there and you didnt even have to write any code! Let your views dictate your Models. You don't have to take your objects and make them 2 dimensional anymore as in the relational world. You can store objects with shape now.
how-to-think-in-data-stores-instead-of-databases
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With