Skip to content

Relationships and Nesting

MongoDB schema-less database hai, iska matlab isme data relate karne ke do main tarike hote hain: Embedding aur Referencing.


1. Embedded Documents (Nesting)

Jab hum ek document ke andar hi doosra document daal dete hain, usse Embedding kehte hain. Ye “One-to-One” ya “One-to-Few” relationships ke liye best hai.

Example:

db.users.insertOne({
name: "Aditya",
address: {
street: "123 Main St",
city: "Delhi",
zip: "110001"
}
});

Fayde:

  • Ek hi query me saara data mil jata hai (Fast Read).
  • Data saath me rehta hai (Locality).

2. Document Referencing (Linking)

Jab hum ek document me doosre document ki _id store karte hain, usse Referencing kehte hain. Ye “One-to-Many” ya “Many-to-Many” relationships ke liye use hota hai.

Example: Humaare paas do collections hain: authors aur books.

Authors Collection:

{ "_id": ObjectId("123"), "name": "J.K. Rowling" }

Books Collection:

{
"title": "Harry Potter",
"author_id": ObjectId("123") // Reference
}

Fayde:

  • Data duplication nahi hoti.
  • Large datasets ke liye better scalability milti hai.

3. Deep Nesting (Bahut andar tak data)

ManguoDB me hum ek doc ke andar doosra, aur uske andar bhi ek aur doc daal sakte hain. Isse hum Multi-level Nesting kehte hain. Ye tab kaam aata hai jab data bahut complex ho.

Deep Nesting ke kuch important points:

  • Hierarchical Data: Ye tree-like structure (jaise comments ke andar replies) store karne ke liye perfect hai.
  • Dot Notation access: Aap nested fields ko asani se parent.child.subchild format me access kar sakte hain.
  • Indexable Fields: Aap deep nested fields par bhi indexes bana sakte hain taaki queries fast rahein.
  • Atomic Updates: Ek hi document ke andar saara nested data update karna “Atomic” hota hai (yaani ya to poora hoga ya bilkul nahi).
  • No Joins needed: Kyunki data ek hi doc me hai, aapko SQL ki tarah complex JOINs ki zaroorat nahi padti.
  • 16MB Limit: MongoDB me ek document ka max size 16MB hota hai, isliye bahut zyada “Deep” nesting se doc size limit exceed ho sakti hai.
  • Read-to-Write Ratio: Agar aapka data aksar sath me read hota hai to nesting best hai, lekin agar nested data bahut zyada update hota hai to performance par hit pad sakta hai.

Example: Maaniyo ek ecommerce app hai jahan hum order details store kar rahe hain:

db.orders.insertOne({
order_id: "ORD123",
customer: {
name: "Aditya",
contact: {
email: "adi@example.com",
phone: "9876543210"
}
},
items: [
{ product: "Laptop", price: 50000 },
{ product: "Mouse", price: 500 }
]
});

Querying Deep Data (Points me samjhein):

Agar aapko nested documentation me se data nikalna hai, to ye points dhyan me rakhein:

  1. Dot Notation use karein: Sabse important rule! Nested field tak pahunchne ke liye . ka use karein. Jaise: "parent.child".
  2. Quotes ka dhyan rakhein: Jab bhi aap dot notation use karte hain ("a.b"), query key ko hamesha double quotes me rakhein. Bina quotes ke MongoDB error de dega.
  3. Exact Match vs Field Match:
    • Agar aap sirf ek field match karna chahte hain, to "parent.child": value use karein.
    • Agar aap poora nested object match karna chahte hain, to { parent: { child: value } } use karein (Lekin isme order matter karta hai, isliye dot notation better hai).
  4. Multiple Nested Query: Aap kitne bhi level tak andar ja sakte hain, jaise "level1.level2.level3.field".

Practical Examples:

Example 1: Basic Dot Notation Maan lijiye humein wo users chahiye jinka city ‘Delhi’ hai jo address object ke andar hai:

db.users.find({ "address.city": "Delhi" });

Example 2: Multiple Fields in Query Agar humein customer ka name AND email dono match karne hain jo alag-alag levels par hain:

db.orders.find({
"customer.name": "Aditya",
"customer.contact.email": "adi@example.com"
});

Example 3: Querying Inside Nested Array Agar items array ke andar kisi product ka price dhoondhna hai:

db.orders.find({ "items.price": { $gt: 1000 } });

(Yahan MongoDB apne aap array ke har element ko check kar lega!)


💡 Quick Q&A: Deep Queries

Sawal: Kya main nested fields par filtering aur sorting dono ek sath kar sakta hoon?

Jawab: Haan, bilkul! Aap dot notation ka use karke filter bhi kar sakte hain aur result ko sort bhi kar sakte hain.

Example: Humein wo orders chahiye jinka customer.city ‘Delhi’ hai aur humein unhe price ke hisaab se sort karna hai:

db.orders.find({ "customer.address.city": "Delhi" })
.sort({ "items.price": -1 }); // Mehenga saman pehle

Sawal: Kya main massive document me se sirf kuch fields select kar sakta hoon?

Jawab: Haan, isse Projection kehte hain. find() ke second argument me 1 (show) ya 0 (hide) pass karein.

Example: Sirf customer ka naam aur email chahiye, baaki kuch nahi:

db.orders.find(
{ "customer.address.city": "Delhi" }, // 1. Filter
{ "customer.name": 1, "customer.contact.email": 1, _id: 0 } // 2. Select (Projection)
);

Embedding vs Referencing: Kab kya use karein?

FeatureEmbedding (Nesting)Referencing (Linking)
PerformanceFast (Read ek baar me)Slow (Multiple queries/lookups)
Data SizeSmall/LimitedLarge/Growing
RelationshipOne-to-FewOne-to-Many / Many-to-Many

Aggregation Lookup (Joins)

Relationship ko join karne ke liye hum $lookup ka use karte hain:

db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "author_details"
}
}
]);

Pro tip: Agar data ka size document limit (16MB) se zyada hone wala hai, to hamesha Referencing ka rasta choose karein! 🚀