frank
frank

Reputation: 1301

MongoDB Schema Design Products with Children Products

In the following blog, there is the example:

http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1

where a Product may have many Parts db.parts.findOne() { _id : ObjectID('AAAA'), partno : '123-aff-456', name : '#4 grommet', qty: 94, cost: 0.94, price: 3.99 }

db.products.findOne() { name : 'left-handed smoke shifter', manufacturer : 'Acme Corp', catalog_number: 1234, parts : [ // array of references to Part documents ObjectID('AAAA'), // reference to the #4 grommet above ObjectID('F17C'), // reference to a different Part ObjectID('D2AA'), // etc ]

I am thinking of doing something similar, except a Product may be made of many Products (ie. they will have the same schema). A Product's environmental impact, would then be the sum of the children Product's environmental impact. These children can in turn be their own Parent Product to other Children Products, like a tree.

To make the design for updates less complicated, if a child's environmental impact has changed, it won't automatically propagate the change up the chain. The parent can see from a children's update timestamp that it is more recent, and has the option to update its fields with a recalculate through the web interface.

I am new to MongoDB, so just want to run this schema design by the community, to see if there are any potential pitfalls to watch out for going with this approach. Thanks.

Upvotes: 1

Views: 96

Answers (1)

Daniele Graziani
Daniele Graziani

Reputation: 496

With the design above the child's environmental impact is not stored in the array of children. So to get the overall environmental impact of a product you will have to run two queries, which may be fine. If it is better to get that result in one query then you have to store the environmental impact of each child in that array.

You mentioned that the children can then have their own children. So you are getting in a tree structure. Take a look at this page for possible solutions:

https://docs.mongodb.com/manual/applications/data-models-tree-structures/

My solution would be to "Model Tree Structures with Array of Ancestors" that way you can get all the descendants in one query and their related environmental impacts. This would involve keeping just the _id in

parts : [{_id: 1}, {_id: 2}, ...]

and then track the parents and grandparents, and great-grandparents, etc. in the ancestors array as such:

ancestors:  [{_id: 3}, {_id: 2}, {_id: 1}, ...]

see the link for a clear explanation of this pattern.

Upvotes: 1

Related Questions