1 - Many Relationship in MongoDB - One to Many

You are here : Home / MongoDB Tutorial


Contents of page >
1) (1-to-Many) One-to-Many Relationships with Embedded documents >
Create STUDENT collections.
Embed the PHONE documents (completely) in the STUDENT document.
It helps in fetching all student and phone data in one query.
1.1) Create collection in MongoDB >


STEP 1.1.1) create and insert in STUDENT collection >
db.STUDENT.insert({
 "_id": 1,
 "FIRST_NAME": "Ankit",
 "PHONE": [
   {"PHONE_NUMBER": 1234},
   {"PHONE_NUMBER": 2345}
 ]
})
db.STUDENT.insert({
 "_id": 2,
 "FIRST_NAME": "Sam",
 "PHONE": [
   {"PHONE_NUMBER": 3456},
   {"PHONE_NUMBER": 4567}
 ]
})


When to use this approach?


When number of  transactions are too high and need to be done atomically >  
This can be used when phone is fetched too frequently. i.e (Read and write operations are too high).


MongoDB does not support transactions on multiple document.But, in MongoDB you can perform atomic operations on a single document.
So, while designing your database and collections you must try and ensure that all the related data (as much as possible) which is needed to be updated atomically must be placed in single document as embedded documents (in form of nest arrays OR nested documents)


1.2 > Now, let’s read/query/find in above MongoDB collection >


Query 1.2.1 > Query to show all students
db.STUDENT.find().pretty()


Output>
{
       "_id" : 1,
       "FIRST_NAME" : "Ankit",
       "PHONE" : [
               {
                       "PHONE_NUMBER" : 1234
               },
               {
                       "PHONE_NUMBER" : 2345
               }
       ]
}
{
       "_id" : 2,
       "FIRST_NAME" : "Sam",
       "PHONE" : [
               {
                       "PHONE_NUMBER" : 3456
               },
               {
                       "PHONE_NUMBER" : 4567
               }
       ]
}


Query 1.2.2 > Query to find all phones of student with FIRST_NAME=”Ankit”
db.STUDENT.find({"FIRST_NAME":"Ankit"}).pretty()


Output>
{
       "_id" : 1,
       "FIRST_NAME" : "Ankit",
       "PHONE" : [
               {
                       "PHONE_NUMBER" : 1234
               },
               {
                       "PHONE_NUMBER" : 2345
               }
       ]
}




2) (1-to-Many) One-to-Many Relationships with Document References >


This is more normalized approach to model one to many relationship.
Most normalized data model, We exactly use this approach in RDBMS (See, below for RDBMS table diagram)
Create separate STUDENT and PHONE collections.
And, documents in phone contain a reference to the student document.
When to use this approach?


This can be used when data is huge.
And when read and write operations are not too high.


2.1) Create collections in MongoDB >


STEP 2.1.1) create and insert in STUDENT collection >
db.STUDENT.insert({
 "_id": 1,
 "FIRST_NAME": "Ankit"
})
db.STUDENT.insert({
 "_id": 2,
 "FIRST_NAME": "Sam"
})

STEP 2.1.2) create and insert in PHONE collection >
db.PHONE.insert({
 "_id": 11,
 "PHONE_NUMBER": 1234,
 "STUDENT_ID":  {
     "$ref": "STUDENT",
     "$id": 1,
     "$db": "mydb"
  }
})
db.PHONE.insert({
 "_id": 12,
 "PHONE_NUMBER": 2345,
 "STUDENT_ID":  {
     "$ref": "STUDENT",
     "$id": 1,
     "$db": "mydb"
  }
})
db.PHONE.insert({
 "_id": 13,
 "PHONE_NUMBER": 3456,
 "STUDENT_ID":  {
     "$ref": "STUDENT",
     "$id": 2,
     "$db": "mydb"
  }
})
db.PHONE.insert({
 "_id": 14,
 "PHONE_NUMBER": 4567,
 "STUDENT_ID":  {
     "$ref": "STUDENT",
     "$id": 2,
     "$db": "mydb"
  }
})

2.2) Now, let’s see above one-many relationship of mongoDB collections in RDBMS (relational database) >


2.2.1) One-Many (1-Many) Relationship - Table structure in RDBMS >


2.2.2) Sql script to create above tables in RDBMS (in oracle) >
create table STUDENT (ID number PRIMARY KEY,
                   FIRST_NAME varchar2(22));

create table PHONE (ID number PRIMARY KEY,
                   STUDENT_ID number,
                   PHONE_NUMBER number,
                   FOREIGN KEY (STUDENT_ID) REFERENCES STUDENT (ID));


2.2.3) Let’s see tables after inserting data in RDBMS >
Here, one student have many phone numbers.

2.3 > Now, let’s read/query/find in above (2.1) MongoDB collections >

Query 2.3.1 > Query to show all students
db.STUDENT.find().pretty()
Output>
{ "_id" : 1, "FIRST_NAME" : "Ankit" }
{ "_id" : 2, "FIRST_NAME" : "Sam" }

Query 2.3.2 > Query to show all phones
db.PHONE.find().pretty()
Output>
{
       "_id" : 11,
       "PHONE_NUMBER" : 1234,
       "STUDENT_ID" : DBRef("STUDENT", 1, "mydb")
}
{
       "_id" : 12,
       "PHONE_NUMBER" : 2345,
       "STUDENT_ID" : DBRef("STUDENT", 1, "mydb")
}
{
       "_id" : 13,
       "PHONE_NUMBER" : 3456,
       "STUDENT_ID" : DBRef("STUDENT", 2, "mydb")
}
{
       "_id" : 14,
       "PHONE_NUMBER" : 4567,
       "STUDENT_ID" : DBRef("STUDENT", 2, "mydb")
}

IMPORTANT Query 2.3.3 > Query to find phone_number=1234 belong to which student >
var phone = db.PHONE.findOne({"PHONE_NUMBER":1234})
var student = phone.STUDENT_ID
db[student.$ref].find({"_id":(student.$id)})

Output>
{ "_id" : 1, "FIRST_NAME" : "Ankit" }



3) Another way to model One-Many relationship of data - (You may use any of the approaches depending on your requirement)


Here we use, one-to-Many Relationships with Embedded References.


Here student is referencing phone.
Embed the phone (only phone_id) in the student data >
3.1) Create collections in MongoDB >


STEP 3.1.1) create and insert in PHONE collection >
db.PHONE.insert({
 "_id": 11,
 "PHONE_NUMBER": 1234,
})
db.PHONE.insert({
 "_id": 12,
 "PHONE_NUMBER": 2345,
})
db.PHONE.insert({
 "_id": 13,
 "PHONE_NUMBER": 3456,
})
db.PHONE.insert({
 "_id": 14,
 "PHONE_NUMBER": 4567,
})


STEP 3.1.2) create and insert in STUDENT collection >
db.STUDENT.insert({
 "_id": 1,
 "FIRST_NAME": "Ankit",
 "PHONE_ID": [
   11,
   12
 ]
})
db.STUDENT.insert({
 "_id": 2,
 "FIRST_NAME": "Sam",
 "PHONE_ID": [
   13,
   14
 ]
})

4) Now let’s cover above point (i.e. 2nd point) - (Inserting related documents in same collection) - One-to-Many Relationships with Document Reference >


4.1) create and insert in STUDENT collection (Also insert related data i.e. data (documents) of PHONE in STUDENT collection) >


db.STUDENT.insert({
 "_id": 1,
 "FIRST_NAME": "Ankit"
})
db.STUDENT.insert({
 "_id": 2,
 "FIRST_NAME": "Sam"
})


db.STUDENT.insert({
 "_id": 11,
 "PHONE_NUMBER": 1234,
 "STUDENT_ID":  1
})
db.STUDENT.insert({
 "_id": 12,
 "PHONE_NUMBER": 2345,
 "STUDENT_ID":  1
})
db.STUDENT.insert({
 "_id": 13,
 "PHONE_NUMBER": 3456,
 "STUDENT_ID":  2
})
db.STUDENT.insert({
 "_id": 14,
 "PHONE_NUMBER": 4567,
 "STUDENT_ID":  2
})



5) Summary -


So in this mongoDB tutorial we learned how to create 1 - many Relationship in MongoDB - Multiple table - one to many.


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.

RELATED LINKS>


eEdit
Must read for you :