I'm modeling a schema. As I'm new to Mongo DB I've no idea on how to model a nosql db. Structuring a relational type db and using mongo on top of it does not allow me to use many to many mapping.
Using Spring-data does provide support for one to many using @DBRef
on top of the List<?>
. But many to many is something I want.
Any help will be deeply appreciated. Kindly prefer using code to explain. Or a demo structure to illustrate. Thanks in advance.
There are several ways to implement many-to-many in MongoDB.
I think the simplest is the following:
Many-To-Many Relational scenario:
After de-normalization:
And your Spring Data code should look something like this:
public class Category {
@Id
private ObjectId id;
private String category_name;
@DbRef
private List<Product> products_ids;
// ... getters and setters ...
}
public class Product {
@Id
private ObjectId id;
private String product_name;
@DbRef
private List<Category> categories_ids;
// ... getters and setters ...
}
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