Migrating data from old collection to new collecton in MongoDB

465 views Asked by At

I have a collection whose data I have to transfer to a new collection. The new collection has some extra fields and I also want to discard some of the fields from the old collection.

Example:

oldCollection { k1:v1, k2:v2, ;k3:v3}
newCollection {k1:v1, k3:v3, k4:v4, k5, v5}

I have to migrate some values and also add new values to the same document while inserting the old data.

1

There are 1 answers

0
Charchit Kapoor On

You can achieve it using an aggregation pipeline something similar to this:

db.collection.aggregate([
  {
    $addFields: {
      x: 1 // add fields to be present in the new collection
    }
  },
  {
    $project: {
      _id: 0 // remove the unnecessary fields
    }
  },
  {
    $merge: {
      into: "newCollection"
    }
  }
])

You can use $out in case your MongoDB version is less than 4.2, in place of $merge. Like this:

{
   $out:  "newCollection"
}