Database Reference
In-Depth Information
{ '$set' : { 'products.*' : product } },
multi = True )
For many-to-many joins, a compromise approach is often best, embedding a list of _id values
rather than the full document:
// db.product schema
{ "_id" : "My Product" ,
"category_ids" : [ "My Category" , ... ] }
// db.category schema
{ "_id" : "My Category" }
Our query is now a bit more complex, but we no longer need to worry about updating a
product everywhere it's included in a category:
def
def get_product_with_categories ( product_id ):
product = db . product . find_one ({ "_id" : product_id })
categories = list ( db . category . find ({
'_id' : { '$in' : product [ 'category_ids' ]} }))
return
return product , categories
Conclusion
Schema design in MongoDB tends to be more of an art than a science, and one of the earlier
decisions you need to make is whether to embed a one-to-many relationship as an array of
subdocuments or whether to follow a more relational approach and reference documents by
their _id value.
The two largest benefits to embedding subdocuments are data locality within a document and
the ability of MongoDB to make atomic updates to a document (but not between two doc-
uments). Weighing against these benefits is a reduction in flexibility when you embed, as
you've “pre-joined” your documents, as well as a potential for problems if you have a high-
arity relationship.
Ultimately, the decision depends on the access patterns of your application, and there are few-
er hard-and-fast rules in MongoDB than there are in relational databases. Using wisely the
flexibility that MongoDB gives you in schema design will help you get the most out of this
powerful nonrelational database.
Search WWH ::




Custom Search