Flatten a object data using Mongo Migration

Viewed 89

I have a mongo collection called fruit-data.in there i have document look like this.

{
  name:Apple,
  weight:100g,
  color:red,
  other_data:{
   havested_by:Jhone,
   havested_from:Rileys Farm,
   city: Oak Glen, California,
   country:USA
 }
}

I want to remove the nested object and get that data to the same level. using mongo migration. I'm using migrate-mongo library.

{
   name:Apple,
   weight:100g,
   color:red,
   havested_by:Jhone,
   havested_from:Rileys Farm,
   city: Oak Glen, California,
   country:USA
 }

The only thing I know. I have to write up() function this. I'm very new to backend.is there mongo specific way to do this?

I have managed to write up a function that looks like this.

up(db, client) {
    return db.collection('fruit-data')
 }
1 Answers

Try update with aggregation pipeline starting from MongoDB 4.2,

  • check condition if other_data field exists true
  • set all object's field and unset other_data object
db.collection('fruit-data').update(
  { other_data: { $exists: true } },
  [{
    $set: {
      havested_by: "$other_data.havested_by",
      havested_from: "$other_data.havested_from",
      city: "$other_data.city",
      country: "$other_data.country"
    }
  },
  {
    $unset: "other_data"
  }],
  { multi: true }
)

Playground


Second option without hardcoding properties,

  • $mergeObjects to merge root document with other_data's fields
  • $replaceRoot to replace above merged object to root
  • unset other_data object
db.collection('fruit-data').update(
  { other_data: { $exists: true } },
  [{
    $replaceRoot: {
      newRoot: {
        $mergeObjects: ["$$ROOT", "$other_data"]
      }
    }
  },
  {
    $unset: "other_data"
  }],
  { multi: true }
)

Playground

Related