Doubt in MongoDB modeling

0

As I studied, when modeling an application using MongoDB you should always think about the application. Thinking of a system that has a Promotion and Gender, where a promotion has a Genre, I saw that it will be necessary a screen to register the promotions and a screen where I will present all the Generos and clicking on all the Promotions of that Genre. In the example above what is the best way to work? Would you do it with ReferenceDocuments or with EmbeddedDocuments? In the case of EmbeddedDocuments how would you look to bring the Generos?

Thank you very much in advance.

    
asked by anonymous 23.05.2017 / 03:24

1 answer

2

Following your requirements you could have a promotion document, where the gender is an attribute. Something like this:

{
  "_id" : "ObjectId("507f191e810c19729de860ea")",
  "tituloPromocao" : "Promoção legal com vários premios",
  "dataInicial" : "2017-05-01",
  "dataFinal" : "2017-05-31",
  "genero" : "genero exemplo"
}

To search for all genres in the promo collection you can use distinct , considering that the collection name is "promo":

db.promo.distinct("genero");

The parameter indicates which field you want to return the different values. It is interesting to add an index in this field, to optimize the search by gender and the distinct itself.

You can save the possible genres in another collection, with a document only, for example:

{
   "generos" : ["Pizza","Calzone"]
}

So you can popular a selection in the interface with the possible options. And it can make another screen to maintain the genres. That way you do not have to do the distinct every time you go get the possible genres. This all considering that your gender is only a String.

Another option would be to consider the genre as a subdocument within the promotion:

{
  "_id" : "ObjectId("507f191e810c19729de860ea")",
  "tituloPromocao" : "Promoção legal com vários premios",
  "dataInicial" : "2017-05-01",
  "dataFinal" : "2017-05-31",
  "genero" : { "id" : "pizza", "descricao" : "Gênero da pizza"}
}

And save the genre in another collection:

{
   "id" : "pizza"
  ,"descricao" : "Gênero da pizza"
  ,"nroPromocoes" : 7
}

This approach would only make sense if you have more information to store the genre, I put the number of promotions there as an example. If this information is very important to the application, if you will access this number very often, then save this value. So you do not have to count the number of deals every time. Keep in mind that this has a cost: If you change the gender description you need to change all promotions that use this gender. If you associate a promotion with a gender, you need to change the promo counter of that gender.

The general guideline on modeling with MongoDB is: Always structure your data thinking about how you will access / modify / insert / delete information .

    
23.05.2017 / 04:12