I am aware that MongoDB is NoSQL Database so it has not similar flexibility like MySQL or other SQL RDBMS.
But we can apply foriegn key in mongoDB in two ways :-
- Using embedded Documents
- Using Field as Reference
Here I have two collections, One is CUSTOMER (Parent) and the Other is ACCOUNT (Child).
**CUSTOMER**
db.createCollection("CUSTOMER",{
validator:{
$jsonSchema:{
bsonType:"object",
required:["CID","CNAME"],
properties:{
CID:{bsonType:"number"},
CNAME:{bsonType:"string"}
}
}}});
{ "CID" : 1, "CNAME" : "Rock" }
{ "CID" : 2, "CNAME" : "Joe" }
{ "CID" : 3, "CNAME" : "James" }
**ACCOUNT** (2nd Collection)
db.createCollection("ACCOUNT",{
validator:{
$jsonSchema:{
bsonType:"object",
required:["BALANCE","CID"],
properties:{
BALANCE:{bsonType:"double"},
CID:{bsonType:"number"}
}
}}});
{ "_id" : 1, "BALANCE" : 20500, "CID" : 1 },
{ "_id" : 2, "BALANCE" : 10000, "CID" : 2 },
{ "_id" : 3, "BALANCE" : 15000, "CID" : 1 },
{ "_id" : 4, "BALANCE" : 20000, "CID" : 2 },
{ "_id" : 5, "BALANCE" : 52000, "CID" : 3 },
{ "_id" : 6, "BALANCE" : 27000, "CID" : 7 }
Here I am treating CID as a foreign key reference But as we can see in the last entry we are entering CID = 7. But it is clear that there is no CID=7 in the CUSTOMER Collection.
My question is how to Prevent other CID value to be inserted which are not in CUSTOMER Collection.
This means it should insert those CID only which are also present in CUSTOMER otherwise it should show ERROR !!
What query should i write so that it check the existence of data in parent before inserting document ?