Database Reference
In-Depth Information
{ desc: "Bring a pot of water to boil.",
materials: ["water", "eggs"] },
{ desc: "Gently add the eggs a cook for four minutes.",
materials: ["egg timer"]},
{ desc: "Cool the eggs under running water." },
]
}
When the two related entities will appear independently in the application, you'll
want to relate. Many articles on MongoDB suggest that embedding comments in blog
posts is a good idea. But relating is far more flexible. For one thing, you can easily
show users a list of all their comments. You can also show all recent comments across
all posts. These features, considered de rigueur for most sites, aren't possible with
embedded documents at this time. 1 You typically relate documents using an object ID .
Here's a sample post:
{ _id: ObjectId("4d650d4cf32639266022018d"),
title: "Cultivating herbs",
text: "Herbs require occasional watering..."
}
And here's a comment, related by the post_id field:
{ _id: ObjectId("4d650d4cf32639266022ac01"),
post_id: ObjectId("4d650d4cf32639266022018d"),
username: "zjones",
text: "Indeed, basil is a hearty herb!"
}
The post and the comment live in their own collections, and it takes two queries to
display a post with its comments. Because you'll be querying comments on their
post_id field, you'll want an index there:
db.comments.ensureIndex({post_id: 1})
We used this one-to-many pattern extensively in chapters 4, 5, and 6; look there for
more examples.
B.1.3
Many-to-many
In RDBMS s, you use a join table to represent many-to-many relationships; in
MongoDB, you use array keys . You can see a clear example of this technique earlier in
the topic where we relate products and categories. Each product contains an array of
category ID s, and both products and categories get their own collections. If you have
two simple category documents
{ _id: ObjectId("4d6574baa6b804ea563c132a"),
title: "Epiphytes"
}
1
There's a popular feature request for virtual collections , which could provide the best of both worlds. See
http://jira.mongodb.org/browse/SERVER-142 to track this issue.
Search WWH ::




Custom Search