Within my database, I store student records that each contain the fields amountOwed
and tuition
.
The task at hand is to update the value of amountOwed
to be the sum of its current value and tuition.
I am considering utilizing a .find
query to retrieve all student documents, iterating through each one and updating the database accordingly.
Though, upon reviewing the mongo documentation, I stumbled upon $set(aggregation)
and $addFields(aggregation)
, but unsure if they are suitable for this operation.
Sample student documents:
{"studentName" : "Student1",
"amountOwed" : 100,
"tuition" : 100
},
{"studentName" : "Student2",
"amountOwed" : 0,
"tuition" : 500
}
The expected output should look like this:
{"studentName" : "Student1",
"amountOwed" : 200,
"tuition" : 100
},
{"studentName" : "Student2",
"amountOwed" : 500,
"tuition" : 500
}
Is there a way to achieve this with just one database query?
Possibly leveraging updateMany
?