2

I want to rename a field that all documents have in my Mongo collection. There's already a great answer for that. But instead of overwriting the current property name, I want to save my renamed property as a new field, leaving the original intact.

Imagine my documents look like this:

{
  "property": "Original property value"
}

I want to obtain this:

{
  "property": "Original property value",
  "property_new": "Original property value"
}

How can I do that?

Ashh
  • 41,249
  • 11
  • 91
  • 120
remidej
  • 1,011
  • 1
  • 11
  • 21

2 Answers2

2

You can use $out aggregation

db.collection.aggregate([
  { "$addFields": {
    "property_new": "$property"
  }},
  { "$out": "newCollection" }
])

It will create a new collection with the name newCollection just rename it with the existing one.

Manoj Selvin
  • 1,911
  • 22
  • 18
Ashh
  • 41,249
  • 11
  • 91
  • 120
1

You simply iterator over the collection elements on mongo shell and update each documents i.e add new attributes as property_new in forEach function as below:

db.st5.find().forEach(function(o) { db.st5.update({"_id":o._id}, {$set: {"property_new": o.property} } )})

Before updating I have insert one document in the collection st5 as:

> db.st5.insert({
...   "property": "Original property value"
... })
WriteResult({ "nInserted" : 1 })
> db.st5.find()
{ "_id" : ObjectId("5c643368b913e399ee84b4f8"), "property" : "Original property value" }

And then iterating over the each elements and updating as below:

> db.st5.find().forEach(function(o) { db.st5.update({"_id":o._id}, {$set: {"property_new": o.property} } )})
> db.st5.find()
{ "_id" : ObjectId("5c643368b913e399ee84b4f8"), "property" : "Original property value", "property_new" : "Original property value" }
> 

Hope this will solve your problem.

krishna Prasad
  • 3,187
  • 1
  • 30
  • 41