Category tree in Mongodb, how to model?

Asked

Viewed 384 times

6

Good night, you guys.

As Mongodb changes a lot our way of modeling a database, I came across a question that can be up to 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 mother and daughter categories. As in the example below:

  • mother category
    • daughter category
    • daughter category
      • daughter category
      • daughter category
    • daughter category
  • mother category
    • daughter category
    • daughter category
    • daughter category

What would be the most correct way to outline this in a single collection? Or the most correct way would be to somehow place these categories within the product collection?

  • The right thing depends on the business model. A type of X structure may not be suitable for an X business model, but it may be the best option for a Y model. The question of how it is, becomes broad and susceptible to responses based on opinions.

  • Just to help, search on "adjacency" and "nested". Example in this article: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

  • From the link you suggested I was able to reformulate my question to google, and not to my surprise, the answer was in the Mongodb documentation itself. I will post as an answer to this question to help others. Thanks.

1 answer

5


In the Mongodb documentation itself there are 5 standards you can follow depending on your application or taste.

Considering the following picture, I will quote two patterns that are available in the Mongo documentation: Estrutura em árvore

Child Reference:

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: http://docs.mongodb.org/manual/tutorial/model-tree-structures/

  • 2

    Thank you very much for your reply, I will also study how non-relational banks work and your response was very helpful, the image you posted was what I imagined. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.