Being one of the most popular NoSQL solutions MongoDB has most of the advantages of this approach. But one issue I'm still struggling with is how reflect object relations in NoSQL data store, specifically - MongoDB.
For example, let's consider a simple data model: User, Post and Comment. It is clear to me that comments have no value on their own and thus become embedded objects for Posts. But when it comes to users - that becomes tricky because User is an entity on its own, not coupled with Post. Now in case I need to list posts with user full names and links to profiles on a web page, I would need to have a list of posts and information about posts authors (name and id at least).
I see 2 possible solutions here:
I'm sure I'm not the first one facing this issue but unfortunately I have not found any best practices on this topic so far. Opinions?
Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N. Let us consider the case of storing addresses for users.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.
In MongoDB, one-to-one, one-to-many, and many-to-many relations can be implemented in two ways: Using embedded documents. Using the reference of documents of another collection.
MongoDB is a non-relational document database that provides support for JSON-like storage. The MongoDB database has a flexible data model that enables you to store unstructured data, and it provides full indexing support, and replication with rich and intuitive APIs.
Both are valid solutions, the advantage of solution 1 is that you can show a page like this with retrieving only one document from the db. Users don't update their profile very often and you can update all posts and embedded comments async after a user profile is changed. You can index the posts and embedded comments on userid so the update should be fast. Updating in mongodb is very speedy because mongodb does an update-in-place and you can't rollback or commit so mongodb doesn't have to log the changes.
However users on sites like stackoverflow also have a reputation and this reputation changes a lot more than their profile.
Solution 2 requires the retrieving of more documents per page, however you can use the $in operator with a list of userid's (userid of post+userid's of comments) so you only need two "selects statements".
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