ZeMoon
ZeMoon

Reputation: 20274

Relational queries in MongoDB

Just started out with MongoDB. I have collections called users, dishes, restaurants and ratings. I need to map the ratings to a particular dish and user.

Users
{
 _id: "12323421",
 name: "John Doe",
 ...
}

Dishes
{
 _id: "9872983749",
 name: "Apple Pie",
 restaurantID: "3432452" //Corresponds to Patisserie
 ...
}

Restaurants
{
 _id: "3432452",
 name: "Patisserie",
 ...
}

Ratings
{
 _id: "74766575",
 userID: "12323421", //Corresponds to John Doe
 dishID: "9872983749", //Corresponds to Apple Pie
 rating: 5
}

I dont know how to go about generating a few queries like:

This is pretty simple to implement in an SQL environment, but how does one use Joins, or nested queries in MongoDB?

Upvotes: 0

Views: 385

Answers (1)

helmy
helmy

Reputation: 9497

MongoDB does not natively support joins or subqueries.

I would suggest that you take a step back and do some reading on MongoDB schema design. The Data Modeling Concepts section of the MongoDB docs is a great place to start. There are many other resources out there on the topic. The O'Reilly book MongoDB Applied Design Patterns is also a great resource.

If you head down the path of modeling your data in MongoDB in a similar manner to how you would model it in an RDBMS, you are setting yourself up for failure.

There is not always a clear "right" or "best" way to model a particular problem. It will always depend on the specific access patterns and requirements for your application.

As you mentioned in a comment, one approach would be to embed the ratings for a particular dish into the Dish collection. But this is problematic if you have a large number of ratings (unbounded growth is bad). A common approach here is often a hybrid. For example, you could embed the most popular or the most recent ratings for a particular dish and store other ratings in a separate collection. Again, think about how your application is going to present the data and try to model your data accordingly.

Upvotes: 2

Related Questions