2

I am trying to write a query to update a date in mongo to be the same as an existing date inside of the same record based on some logic. I have a simple step that I am stuck on how do I access the value?

db.getCollection("MyCollection").updateMany({
//SOME LOGIC HERE
{
"$set":{"updatedTs": "$$createdTs"}
},{multi:true}
)

This returns updatedTs being equal to the literal string "$$createdTs" and not the value stored. The closest I've found to my query is this forum question but the page linked no longer exists: https://www.mongodb.com/community/forums/t/updatemany-in-mongodb-using-value-of-other-field/99555

What am I missing here?

Daniella
  • 171
  • 2
  • 3
  • 14
  • use the set the aggregation way with `[{"$set": {"updatedTs": ...}}]` https://stackoverflow.com/a/37280419/13583510 – cmgchess May 09 '23 at 18:02
  • @cmgchess Thank you! I will take a look. Looks like I missed the aggregate brackets. – Daniella May 09 '23 at 18:12
  • 1
    Thanks that's what was missing! I needed to add [] around set before {multi:true} and remove one of the $ in createdTs. That worked. I can accept your answer if you want to write that. This has puzzled me for a whole day thank you! – Daniella May 09 '23 at 18:15
  • sure i added an answer – cmgchess May 09 '23 at 18:22

1 Answers1

2

from MongoDB 4.2 onwards you can write aggregation pipeline inside update queries (i.e includes updateMany).

db.getCollection("MyCollection").updateMany({
//SOME LOGIC HERE
},
[
 {
  "$set":{"updatedTs": "$createdTs"}
 }
],
{multi:true}
)

mongoplayground

cmgchess
  • 7,996
  • 37
  • 44
  • 62