Issue when using $set - does not use existing attribute data

Hello,

Please note that starting 4.2 you can use aggregation pipelines for updates and the use $set is supported.

I checked the snippet you shared and I see $set is not enclosed in which makes it a pipeline.

Please check the example below which I tested in my environment showing the correct value of $sampleData2 being assigned instead of the literal value:

MongoDB Enterprise M040:PRIMARY> db.products.insertOne({"sampleData2":123})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("63613bf818cb6cb9c0c2fb4a")
}

MongoDB Enterprise M040:PRIMARY> db.products.find()
{ "_id" : ObjectId("63613bf818cb6cb9c0c2fb4a"), "sampleData2" : 123 }

MongoDB Enterprise M040:PRIMARY> db.products.update({  "sampleData2": {    $exists: true  }},[{$set: {"sampleData3": "$sampleData2"}}])
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

MongoDB Enterprise M040:PRIMARY> db.products.find()
{ "_id" : ObjectId("63613bf818cb6cb9c0c2fb4a"), "sampleData2" : 123, "sampleData3" : 123 }

Please also check to the different aggregation pipeline stages you can use for updates in this documentation link.

I hope you find this helpful.

Regards,
Mohamed Elshafey

2 Likes