Reputation: 13
I am new to MongoDB and I am creating a database to keep records of students and the courses that the students are doing at a university. There are three collections called Student, Subject and Lecturer. The Student collection contains studentId, name,dob,email,year. The Subject collection contains the subjectId, subjectName,credits The Lecturer collection contains the lecturerId, lectureName, speciliazation, contactNo, email. The relationship between Student and Student collection is many to many. Between Subject and the Lecturer collection there is a one to one relationship. I need to add the subjectId to the student collection and lecturerId to the subject collection.. Can anyone please tell me how can I create foreign key relationships between collections?
Upvotes: 1
Views: 12065
Reputation: 1498
You can use MongoDB DBRefs where a document contains references from different collections.
There are three fields in DBRefs −
$ref
− This field specifies the collection of the referenced document
$id
− This field specifies the _id field of the referenced document
$db
− This is an optional field and contains the name of the database in which the referenced document lies
Student's document example -
{
"_id":ObjectId("53402597d852426020000002"),
"subjects": [{
"$ref": "SubjectCollection",
"$id": ObjectId("534009e4d853427820000001"),
"$db": "dbname"
},{
"$ref": "SubjectCollection",
"$id": ObjectId("829009e4d856727320000007"),
"$db": "dbname"
}],
"name": "Mukesh Saini",
"dob": "01-01-1990",
"email": "[email protected]",
"year": 2017
}
Then you can query the referenced document as follows -
var student = db.studentsColl.findOne({"name":"Mukesh Saini"})
var dbRef = student.subjects[0]
db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
Upvotes: 10