Database Model reference - DBRefs in MongoDB

You are here : Home / MongoDB Tutorial



Contents of page >


1) What are DBRefs in mongoDB?
DBRefs are easy way to represent a document in MongoDB.
2) DBRefs include following 3 important fields >
$ref - Name of the collection where the referenced document is there.
$id - It is  _id value of referenced document.
$db - It represents the database in which reference document is there (It’s Optional).
3) Example of using DBRefs in MongoDB >


3.1) create and insert in ADDRESS collection >
db.ADDRESS.insert({
 "_id": 11,
 "CITY": "Delhi"
})
db.ADDRESS.insert({
 "_id": 12,
 "CITY": "London"
})


3.2) create and insert in STUDENT collection >
db.STUDENT.insert({
 "_id": 1,
 "FIRST_NAME": "Ankit",
 "ADDRESS_ID": {
     "$ref": "ADDRESS",
     "$id": 11,
     "$db": "mydb"
  }
})
db.STUDENT.insert({
 "_id": 2,
 "FIRST_NAME": "Sam",
 "ADDRESS_ID":  {
     "$ref": "ADDRESS",
     "$id": 12,
     "$db": "mydb"
  }
})


3.3) Now, Query using dbRef in MongoDb collection to Find address of student with FIRST_NAME=”Ankit”
var student = db.STUDENT.findOne({"FIRST_NAME":"Ankit"})
var studentAddress = student.ADDRESS_ID
db[studentAddress.$ref].find({"_id":(studentAddress.$id)})
Output>
{ "_id" : 11, "CITY" : "Delhi" }


4) Summary -
So in this MongoDB tutorial we learned that DBRefs are easy way to represent a document in MongoDB.


DBRefs include following 3 important fields >
$ref, $id and $db
$ref - Name of the collection where the referenced document is there.
$id - It is  _id value of referenced document.
$db - It represents the database in which reference document is there (It’s Optional).


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>

What is MongoDB - A quick introduction to database

Difference in MongoDB and RDBMS - What are Database, collection, document and field in MongoDB

Update documents in collection in mongoDB

Delete documents in collection (table) in mongoDB

How to Delete all documents from collection in MongoDB

See list of all databases in MongoDb, switch database

Create new collection(table) in mongoDB


Labels: MongoDB
eEdit
Must read for you :