Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many in mongodb using spring configuration(annotation preffered)

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.

like image 832
HVT7 Avatar asked Aug 12 '14 11:08

HVT7


1 Answers

There are several ways to implement many-to-many in MongoDB.

I think the simplest is the following:

Many-To-Many Relational scenario:

Many-To-Many Relational scenario

After de-normalization:

After de-normalization scenario

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 ...

}
like image 143
marianomdq Avatar answered Oct 19 '22 12:10

marianomdq