I am using MongoDB at work these days. So far, I find it a great experience.
However I am asked to make relations between collections with MongoDB. This goes against the purpose of the NoSQL concept to me but being a good old noob in this area, I came to ask for other opinions.
For example if we take the common Role / User relationship, is it possible to have a reference collection named "Roles" and to attribute a reference of one item to a User item?
I started thinking about creating an object which provides an ID to the object requested but it feels like something I should not have to do with NoSQL.
So are there people here who have been ask to do the same thing? Did you succeed and how?
MongoDB (and most other NoSQL databases) do not natively support the concept of relations. RDBMSs have native query tools to define and make use of relationships (JOINs, for example) that MongoDB lacks.
This doesn't mean you cannot define relationships/references in NoSQL databases. It simply means there are no native query operators that are relation aware.
There are three different ways to "refer" to one document from another in MongoDB :
Store the referred document's ID (usually an ObjectId) as a field in the referring document. This is the best approach if your app will know in which collection it has to look for the referred document. Example : {_id: ObjectId(...); userId: ObjectId(...) <- reference).
The second approach is using the DBRef convention which defines a reference to a document in a formalized way : { $ref : <collname>, $id : <idvalue>[, $db : <dbname>] }
. In almost all cases the first approach is preferred but DBRef does allow references to document the application may not know the type or location of. Furhter information here : http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef and a good read on when to use them here : http://valyagolev.net/article/mongo_dbref/
Not technically a reference but in a lot of cases it makes sense to embed (parts of) documents into other documents. Note that normalization of your schema should be less of a focus with NoSQL databases. Example : {_id: ObjectId(...); user: {_id: ObjectId(...), name:"Willy Wonka"}}
.
All that said, you can use a completely normalized schema in MongoDB and most ORM libraries will do a lot of the work for you that is not native to MongoDB. In most case this does mean you'd be better off with a traditional RDBMS though. If you're switching to MongoDB because you think it's a fast version of MySQL you have been misinformed. Both have functional sweetspots with only limited overlap. If your app relies heavily on relational functionality don't use NoSQL.
Other articles worth reading to get you up to speed on non-relational thinking : http://www.mongodb.org/display/DOCS/Schema+Design