Mongo Db parents and children tags related to othe

2019-08-04 16:57发布

Well , i'm going to set up my mongo db schema for a little site, what i need is to reproduce this schema into mongo db collections:

product
        -> tag1
              ->child_tag1
              ->child_tag2
        -> tag2
              ->child_tag1
              ->child_tag2
        -> tag3
              ->child_tag1
              ->child_tag2

which is the best way to reproduce this schema with mongo ?

For sure i need to be able to change a tag or child tag without update all collection objects :) [EDITED]

Well cause of i know my question is not so clear, i need to clarify that i'm trying converting a mysql db site onto a mongoDb site.

So i have 4 tables in mysql:

products

id(AUTO) | product_name | qty
 1          biscuits      34
 2          limonade      29

tags

id(AUTO) |  tag_name 
  1            sugar
  2            eggs
  3            vitamine C

tags_childs

id(AUTO) | id_tag | tag_child_name
  1          1        glucouse
  2          2        protein
  3          2        chicken
products_tags

id_product | id_tag | id_tag_child 
  1            1         NULL
  1            1         1
  1            2         3
  2            3        NULL

so i use products_tags table to join over 4 tables (and this is why heating joins i'm switching to mongoDb :))

so i can reproduce this scenario with mongodb collections and objects?

thx :)

1条回答
家丑人穷心不美
2楼-- · 2019-08-04 17:26

Just wanted to make sure I'm understanding what your above document shows; essentially Many Products can have Many Tags, and Tags can have children under them (Coding tag -> Php is child tag of Coding).

With that being my understanding of the above question here's how I would structure your Mongo Collections:

Products Collection:

{
   "ProductName":"Sweet Jelly",
   "Qty":9,
   "Tags":[
     ListOfTagIds
    ]
 }

The list of TagIds would be the Unique Identifiers which mongoDB automatically assigns to each of the new fields created.. see here

From there I'd create a Tags Collection:

{
  "TagName":"Coding Languages";
  "ChildTags":[
      $_idOfChildren
   ]
}

Then if your tag had a child:

{ 
  "TagName":"PHP",
}

For this Parent / Child relationship you can read a bit more about it from this excellent mongo resource located here: Mongo Book - Page 16 starting with No Joins.

Good Luck!

查看更多
登录 后发表回答