Skip to main content

๐Ÿ‘ Change genres in books

We want to modify the MongoDB schema so that each book's genres are represented as an array of strings. We'll have data duplication, as genres will get copied on each book. This is a good strategy if the duplicated data does not change often.

We'll go from the proposed array of objects:

bookGenres: [
{
"bookId": "Some Book Id",
"genres": "fiction"
},
{
"bookId": "Some Book Id",
"genres": "novel"
}
]

to an array of

genres: [ 
{ "name": "fiction" },
{ "name" :"novel" }
]
  • On the MongoDB diagram view, click the books collection.
  • Click on the edit icon of genres. Deselect id, This is a child relationship of bookGenres, and we'll merge these fields into the parent, to avoid too much unneccesary nesting.
  • Click Save and close.
  • Click on the edit icon of the book_genre embedded array.
  • Change the field name from bookGenres to genres.
  • Uncheck bookId and genreId.
  • Click Save and close.
Changes in the books collection