I have student documents in my database. Each document is a student and has the fields amountOwed
and tuition
.
I am trying to update the amountOwed
to be equal to the current value of amountOwed + tuition.
I've thought about using a .find
query to get all the student documents, looping through each document and updating the database.
I've also researched and found the $set(aggregation)
and $addFields(aggregation)
in the mongo documentation but I'm not sure if I can use that for what I'm trying to do.
Example documents:
{"studentName" : "Student1",
"amountOwed" : 100,
"tuition" : 100
},
{"studentName" : "Student2",
"amountOwed" : 0,
"tuition" : 500
}
Output should be:
{"studentName" : "Student1",
"amountOwed" : 200,
"tuition" : 100
},
{"studentName" : "Student2",
"amountOwed" : 500,
"tuition" : 500
}
Is there any way to do this all within one database query?
Maybe using a updateMany
?