How can we assign one field value to another?

I want to assign one field value (existing field) to another field (new one) inside embedded (means array if hashes). In short I wanna create new key-value pair, where key is static but value is another field’s value.

Welcome to the MongoDB Community @Dhara_Pathak!

To help us provide relevant advice, please comment with:

  • an example document before & after the change you want to make

  • your version of MongoDB server

You may find Formatting code and log snippets in posts tips handy for improving readability.

Thanks,
Stennie

1 Like

Hi @Stennie,

Thanks for the advice.

My MongoDB server version: 4.2.5

Here is what I’m trying to do:

  • I have one column: invoices.services.price
  • where services is embedded in invoices
  • now I want to create new column called invoices.services.unit_price and copy values from invoices.services.price

Hi @Dhara_Pathak,

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

You haven’t provided an example document, but based on your description I assume something like the following would be representative:

db.mydata.insert({
    invoices: {
        services: {
            price: NumberDecimal("4.99")
        }
    }
})

Updating with an aggregation pipeline to copy price to a new unit_price field:

db.mydata.update(
    // Match all documents
    {},
    // MongoDB 4.2+ can use an aggregation pipeline for updates
    [{
        $set: {
            "invoices.services.unit_price": "$invoices.services.price"
        }
    }]
)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Checking the resulting document:

db.mydata.find().pretty()
{
	"_id" : ObjectId("60b623967440f0f009e0a6ff"),
	"invoices" : {
		"services" : {
			"price" : NumberDecimal("4.99"),
			"unit_price" : NumberDecimal("4.99")
		}
	}
}

There have been quite a few minor server releases since 4.2.5 was released in March, 2020. Minor releases do not introduce any backward-breaking compatibility issues or behaviour changes within the same server release series so I’d recommend updating to the latest 4.2.x release (currently 4.2.14) . The Release Notes for MongoDB 4.2 have more details on specific bug fixes and improvements in minor releases.

Regards,
Stennie

1 Like

Thank You so much @Stennie !

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.