简体   繁体   中英

MongoDB Many-to-Many relationship

I am new to MongoDB and I am trying learn NoSQL style of databases and wanted to know, how would I write a many-to-many relationship in MongoDB command line. For example, restaurants can receive comments from one or more user, and each of those users can comment on one or more restaurant.

Restaurants: Comment ID, User ID, Comment

Users: Comment ID, Restaurant ID, Comment

Would we code in a unique ID?

If your system suppose to perform queries with different kind of relations (joins) I'd suggest to re-design it and turn to a relative database.

In case of Mongo you'll have to manage relations manually. You can use DBRef . But I'd strongly recommend to avoid them. In many frameworks (eg - Spring Data) DBRefs may cause non-optimal sub-queries (it performs a single sub-query in a cycle for each DBRef in the results set).

In your case I'd suggest to store the list of related Primary Keys - IDs - in each entity and implement a query by the list by your own IF needed.

With NoSQL, the main thing to look at is how you expect to be querying for this data. You want to avoid relationships as much as possible, and often will want to encapsulate data in a single document. Many-to-many relationships will often end up denomormalized, and A has B relationships will often end up with B as a property within A .

Looking at your example for comments <-> restaurants, it might make sense to have a comments array on a restaurants collection that you push into when you add new comments. Assuming that no restaurant has too many comments (which is definitely possible to work around!) this will allow you to get all of the information that you want in a single, fast query.

If you also want to look up comments by user, you might denormalize each user's comments and also store them on the user, or perhaps just store the ids of the restaurants that that user has commented on.

Storing data this way is definitely more work and is less flexible than doing this with a traditional relational database, but it does allow for fast queries & a decently scalable architecture

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM