remidej
remidej

Reputation: 1645

Copy and rename a document field in MongoDB

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?

Upvotes: 2

Views: 2551

Answers (2)

Ashh
Ashh

Reputation: 46451

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.

Upvotes: 3

krishna Prasad
krishna Prasad

Reputation: 3812

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.

Upvotes: 1

Related Questions