Skip to content
Advertisement

MongoDB attribute to array migration script

I’m trying to make a migration for a database, which has the following structure as of now:

JavaScript

There have been some changes in how we need to handle a site, having now the possibility to have multiple sites, and not only one.

So I need to change the DB to look like this:

JavaScript

Is there a way to change the schema with a simple migration script to have each site inside a ‘sites’ array?

Any help would be appreciated.

I can share more information if needed.

EDIT:

The structure where the site is an object, inside nested objects as follows:

JavaScript

How can I access this specific stage I need?

EDIT 2: Full structure:

The collection ‘tickets’ will have numerous entries of tickets, whose structure for all needs to be changed to what we talked about before. The specific structure is as follows:

JavaScript

The structure I want to map is the following:

JavaScript

This is because future tickets will have two sites, so I want to change the structure of the existing ones to a sites configuration. Now, inside the ticket I don’t have anything that says ‘site’, I get everything from another database called configuration.

So far I have the following, but I don’t know if it’s correct:

JavaScript

Advertisement

Answer

Yes, you can do this in a single update using pipelined updates and $replaceRoot, like so:

JavaScript

Mongo Playground


EDIT

Here’s how to do it for the full structure you provided, I had to make some assumptions as some things weren’t exactly clear. For example a “stage” that has the “substages” field will be converted, others will not per you sample.

JavaScript

Mongo Playground

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement