many to many - MongoDB, relation between documents or collections -
i'm pretty new nosql, mongodb. how deal many-to-many relation between 2 or multiple collections/documents? we'd better use dbrefs or embed? i've read mongodb manual, didn't find many-to-many relation. missed points? or there no kind of relation in mongodb? thx!
embed versus reference
this problem of embedding versus referencing, , it’s common source of confusion new users of mongodb. there’s simple rule of thumb works schema design scenarios: embed when child objects appear in context of parent. otherwise, store child objects in separate collection.
embed or reference depends on application. suppose you’re building simple application in mongodb stores blog posts , comments.if comments appear within blog post, , if don’t need ordered in arbitrary ways (by post date, comment rank, , on), embedding fine. if, say, want able display recent comments, regardless of post appear on, you’ll want reference. embedding may provide slight performance advantage, referencing far more flexible.
many-to-many
in rdbmss, use join table represent many-to-many relationships; in mongodb, use array keys. example each product contains array of category ids, , both products , categories own collections. if have 2 simple category documents
{ _id: objectid("4d6574baa6b804ea563c132a"), title: "epiphytes" } { _id: objectid("4d6574baa6b804ea563c459d"), title: "greenhouse flowers" } then product belonging both categories this:
{ _id: objectid("4d6574baa6b804ea563ca982"), name: "dragon orchid", category_ids: [ objectid("4d6574baa6b804ea563c132a"), objectid("4d6574baa6b804ea563c459d") ] }
Comments
Post a Comment