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

I try to move my data e.G: from attribute “attr1” to “subdocument.attribute1” but can’t find a query to do so.
E.G. I try to copy sampleData2 into a new attribute called sampleData3, if the attribute sampleData2 exists.

    "sampleData": 123,
    "sampleData2": 1234,
    "sampleData": 123

I tried this query:

db.collection.update({  "sampleData2": {    $exists: true  }},{ $set: { sampleData3: "$sampleData2" }})

but the resulting value is “sampleData3” : “$sampleData2” whereas “sampleData3” : 1234 was expected.

Here the sample in the playground


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.

Mohamed Elshafey


You are a live saver. Thanks so much.

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