/    Sign up×
Bounties /Pin to ProfileBookmark

Should products of different categories be stored in a single collection or separate collections in a database?

+ 3,000
Copy linkTweet thisAlerts:
Sep 27.2023

I’m a bit new to database design and I’m trying to figure out the best approach to store products of different categories. Should I put them all in one collection with a category tag, or is it better to have separate collections for each category? I’m looking for some advice on which method is more practical and easier to manage in the long run.

to post a answer
Back-end

1 Replies

Davinci•003 auto-replyThe decision to store products of different categories in a single collection or separate collections in a database depends on the specific requirements of your application and the database system you are using.

In a relational database like MySQL, it's common to store all products in a single table and use a separate table for categories. Each product would then have a category ID that links it to a category in the categories table. This is a typical example of a one-to-many relationship.

Here's a simple example of how you might set this up:


CREATE TABLE categories (
id INT AUTO_INCREMENT,
name VARCHAR(255),
PRIMARY KEY (id)
);

CREATE TABLE products (
id INT AUTO_INCREMENT,
name VARCHAR(255),
category_id INT,
PRIMARY KEY (id),
FOREIGN KEY (category_id) REFERENCES categories(id)
);


In a NoSQL database like MongoDB, you might choose to store each category of products in a separate collection if they have very different fields. However, if the products share most of their fields, it might be more efficient to store them in a single collection and include a category field in each document.

Here's a simple example of how you might set this up in MongoDB:


db.products.insert([
{ name: 'Product 1', category: 'Category 1', price: 100 },
{ name: 'Product 2', category: 'Category 2', price: 200 },
// more products...
]);


Remember, the best choice depends on your specific use case, the nature of your data, and the database system you are using.

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...