Categories tree in MongoDB, how to model?

6

Good night, guys.

As MongoDB changes a lot of our way of modeling a database, I came across a question that may be half-beast.

I'm doing a Restful API using Lumen and MongoDB as a database, and I want to create a collection of product categories, and these categories have their respective mums and daughters categories. As in the example below:

  • parent category
    • child category
    • daughter category
      • child category
      • child category
    • child category
  • parent category
    • child category
    • child category
    • child category

What would be the most correct way to lay out this in one collection? Or would the correct way be, somehow, put these categories within the product collection?

    
asked by anonymous 07.10.2015 / 04:49

1 answer

5

In MongoDB's own documentation there are 5 patterns you can follow depending on your application or taste.

Considering the following image, I will cite two standards that are available in the Mongo documentation:

ChildReference:

db.categories.insert({_id:"MongoDB", children: [] } )
db.categories.insert( { _id: "dbm", children: [] } )
db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )
db.categories.insert( { _id: "Languages", children: [] } )
db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )
db.categories.insert( { _id: "Books", children: [ "Programming" ] } )

And the Parent Reference :

db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
db.categories.insert( { _id: "dbm", parent: "Databases" } )
db.categories.insert( { _id: "Databases", parent: "Programming" } )
db.categories.insert( { _id: "Languages", parent: "Programming" } )
db.categories.insert( { _id: "Programming", parent: "Books" } )
db.categories.insert( { _id: "Books", parent: null } )

Source: link

    
07.10.2015 / 16:47