Search code examples
mongodbmongodb-queryliquibase

Migrate datat MongoDB in liquibase


I have in mongo 2 collections that look something like this:

collection1:

{
"id": "someId",
"name": "someName"
}

colleciton2:

{
"_id": "id",
"objectOfTypeCollection1": [{
    "id": "someId2",
    "name": "someName2"
    }]
}

After the migration I need to have: collection1:

{
"id": "someId",
"name": someName
},
{
"id": "someId2",
"name": "someName2"
}

This is easly done with some javascript code, but I need to have this migration in Liquibase, which means using runCommand. As of now I am unaware of a way to have a find command inside the update command in order to manage to move the data from collection2.objectOfTypeCollection1 into collection1.

To put it simple, can you use JS in runCommand?


Solution

  • Use $merge

    db.runCommand( {
       aggregate: db.collection2.getName(),
       pipeline: [ 
       {  $unwind: "$objectOfTypeCollection1" },
       {
          $merge: {
             into: db.collection1.getName()
          }
       } 
       ],
       cursor: {}
    } )