Saturday 21 February 2015

Designing one-to-many mapping in mongoDB


In one-to-many relationship one entity maps to many entities.

Example
company – employees
city – people
post - comments

One company has many employees. Many people live in one city. One post can have many comments.

There are two ways to model one-to-many mapping.
1.   Embed documents
2.   Separate documents

Embed documents
You can embed all employees inside company.

{
        "_id" : 1,
        "company_name" : "ABC",
        "employees" : [
                {
                        "id" : 1,
                        "name" : "Hari Krishna"
                },
                {
                        "id" : 2,
                        "name" : "Dhrona"
                }
        ]
}


Separate Documents
You can create one collection for company and another collection for employees and refer company id in employee collection.

Company collection
{ "_id" : 1, "company_name" : "ABC" }

Employee collection
{ "_id" : 1, "company_Id" : 1, "name" : "Hari Krishna" }
{ "_id" : 2, "company_Id" : 1, "name" : "Dhrona" }
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment