best practice for nested category in Mongo and Met

2019-09-12 15:27发布

I want to handle nested category in Mongo and Meteor framework for several Ads. For example like this:

Ads object have category field like this:

MainCategory_1 > SubCategory_1.1 > SubCategory_1.1.1 > SubCategory_1.1.1.1 > { Ad_1 HERE }
               > SubCategory_1.2 > SubCategory_1.2.1
               > SubCategory_1.3 

MainCategory_2 > SubCategory_2.1 > SubCategory_2.1.1 > SubCategory_2.1.1.1 
               > SubCategory_2.2 > SubCategory_2.2.1
               > SubCategory_2.3 

for example Ad_1 object belongs to SubCategory_1.1.1.1

And also I want to access Ad_1 with queries like this:

All MainCategory_1 All SubCategory_1.1 All SubCategory_1.1.1 All SubCategory_1.1.1.1 And All SubCategory3

I have two approaches:

  1. Store cat_id for each object and merge result on multiple query.
  2. Store category as string of path and query on that string field. Like this answer.

I want to know which one is better??

Do you know other approach with better performance and simplicity??

1条回答
beautiful°
2楼-- · 2019-09-12 15:49

It highly depends on the relationship between your objects (i.e. the ratio of number of objects on each side of the relationship, and the frequency of updates) so it depends on your application and requirements.

A good resource to look at (which you might take as 'best practice') is the blog from MongoDB about denormalization:

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

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

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

in very short, because it's a wide subject: we're talking about N-N relationship, and it depends on the ratio of N's

If objects are immutable, it's recommended to nest them in another object since you won't have to deal with updates and search is made trivial.

If objects are not immutable, you have to weight the cost of updates versus the cost of searching through a collection to look up ID then search through the other collection for the objects associated with that/those IDs.

查看更多
登录 后发表回答