I'm working on a ecommerce project based on MERN Stack. when a user land on my product search page, i have to fetch list of all flavours & categories that are available for search.
i know two ways to do it (described below) & i don't know which one is better || their is a better option.
store all flavour and categories in an array (in other document) and update them when ever a new product with a new cat&flav added.
or use db.collection.distinct() on products collection. to fetch all distinct flav and categories.
I know the 2 way is easier than 1 , but what if i have 10,000 or 1 million products or more.
then what is better for performance, is first one is better (faster) or it doesn't matter, like both are fine. I'm confused.
CodePudding user response:
I think the second way is better , because when you want to add new product you didn't need update
and use insert
and its more simpler than of update
CodePudding user response:
Dont go with the first option as it will make your backend code messier.
THe second option is good if the volume of the data is lesser.
Since you have data of volume 10,000 or 1 million below is the method I would suggest.
Create index on the key in question
db.collection.createIndex({"someKey": 1})
Use aggregation to fetch the unique values.
db.collection.aggregate([
{
"$sort": {"someKey": 1},
},
{
"$group": {
"_id": "$someKey"
}
},
{
"$group": {
"_id": null,
"distinctValues": {"$push": "$_id"},
}
},
], {allowDiskUse: true})
Let me know in the comments if you have any further queries.