Prakhar Singh
Prakhar Singh

Reputation: 57

Migrating data from old collection to new collecton in MongoDB

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.

Upvotes: 0

Views: 575

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

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"
}

Upvotes: 0

Related Questions