How can we assign one field value to another?

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

3 Likes