Best way to store products and its attributes information in mongodb

I have a products table in which data is stored based on its category(e.g Cakes, Chocolates, Flowers etc.) and attributes and attributes_val table which have a values like (Weight, Eggless, Picture_on_Cake, Size etc.) and (1kg, 2kg, 3kg, true, false etc.) respectively. Can somebody please guide me what is the best way to store this information in mongodb?

Hi @Lalit_kashyap ,

Its a bit of a complex question as the way you store the data should be according to your queries and predicts.

The main guidance in MongoDB is that data that is queried together should probably be stored together whithin a document.

Without the queries and update patterns I can only give you a partial example.

In my opinion a document with all the data in it can do the job probably.

_id : ... ,
ProductName : ...,
Category : ... ,
Attributes : {
       Size : ..., 
       Picture_On_cake : ... 


Since MongoDB is flexible schema the attributes can different between objects.

See antipattern article for more info

Another one of interest is a different pattern


Hi @Pavel_Duchovny, thanks for the quick response. Suppose i have a five attributes associated with single product, do i need an array of attributes for each unique product. I mean, suppose i have a product category(cake), which could have chocolate, black forest, red-velvet … types of cakes having attributes Weight(1kg,2kg,3kg etc) and Heartshape(true or false), Eggless(true or false). Should i have to map individual attribute value with the product?

Also, suppose if i have a total of 5000 different products in different category, will i create 5000 individual mongodb documents in a single collection or embed all products info in a single document(which could exceed the default mongodb document size limit in my case)?

Hi @Lalit_kashyap ,

For the first part, do you mean that you will have individual fields vs an array of key values? It really depends on the application purpose.

The key-value attribute pattern is there to reduce an index footprint to search on any of the key values to find a product. If searching based on attributes or maybe compound attributes in a search.

If the idea is only to list product attributes when a category or a specific product is searched having straight field per attributes make more sense.

Regarding the second question I would say definitely document per product and index the category field to better find per category documents.

Having a single document for every category will risk you :

  • unbounded arrays
  • growing over allowed size
  • concurrency issue when multiple update the same doc.
  • hard scaling with MongoDB further.


1 Like