In
one-to-one relation, each item corresponds to exactly one item.
Example
Employee-Resume
student-marksSheet
customer-transaction
person-passport
One
employee has one resume associated with it. One resume corresponds to one employee.
One
student has one marks sheet and one marks sheet associated with one student.
Let’s
try to model this one to one mapping for student-markssheet.
There
are three ways we can model this relation
1.
Embed marks_sheet document in student document
2.
Embed student document in marks_sheet document
3.
Define student and marks_sheet documents separately.
Embed markssheet
document in student document
First
way is we can embed marks_sheet document in student document.
{ "_id" : 512, "firstName" : "Hari Krishna", "lastName" : "Gurram", "marks_sheet" : { "mathematics" : 98, "physics" : 85, "chemistry" : 79 } }
Embed student
document in marks_sheet document
Second
way is we can embed student document in marks_sheet document.
{ "_id" : 1, "mathematics" : 98, "physics" : 85, "chemistry" : 79, "student" : { "id" : 512, "firstName" : "Hari Krishna", "lastName" : "Gurram" } }
Define student and
marks_sheet collections separately.
student
document contains a filed “marks_sheet_id” which is used to identify
“marks_sheet” document.
{ "_id" : 512, "marks_sheet_id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram" }
marks_sheet
document contains a field “student_id”, which is used to identify “student”
document.
{ "_id" : 1, "student_id" : 512, "mathematics" : 98, "physics" : 85, "chemistry" : 79 }
Ok cool, so I had
three ways, which one I have to use
It
is totally depends on type of data you are going to model. Below are the key
points you need to consider while choosing approach.
1.
Frequency of access
If you are going to access student
documents more frequently and marks_sheet document less frequently, then define
student and marks_sheet documents separately. It is because if you go for
embedding documents approach, you are unnecessarily loading marks_sheet
document, whenever you loads student document.
2.
Size of document
If the embedded document size is very large,
and even of you want to update outer document (not embedded), you have to load
entire document. So in this case separate documents.
No comments:
Post a Comment