xunux
xunux

Reputation: 1769

Performing single operation to add/subtract a value from a field across multiple docs in a collection with mongoose

Assume a series of docs like below

{prevBalance:30,order:1,mod:-10,total:20},
{prevBalance:20,order:2,mod:20,total:40},
{prevBalance:40,order:3,mod:-10,total:30},

Notice that they have an "order" and that each consecutive doc depends on a value from the previous one. This is a simplified version of a sort of statement tracking functionality, in which a document has some sort of temporal dependency on a previous document. Naturally, this is not a spreadsheet, so to allow a change in the "past" documents, i would need some sort of cascading write operation to each sequential document.

For example, if I want to modify the order:1 document and change its previous balance to 40, then its total would also also be recalculated to 30, and i would need the cascading operation in the next 2 documents, adding 10 to prevBalance and total for each of those docs.

My question is if it's possible to do this with aggregation somehow, or any other way really, so that I can just use a single mongoose or mongo command to perform an addition on 2 fields of every doc of an array.

My first thought was to just do a loop for each doc, but this seems like a terrible idea, since it would require n read/writes to the db from the server.

Is there a way to do something like Model.updateMany({order:{$gt:1}},{prevBalance:{$add:10},total:{$add:10}}) I can;'t find a clear documentation of the kind of operations I can do like that, and with aggregation $add seems to expect to just add values of documents together, but not actually update the values in the db.

Any suggestions are appreciated thanks!

Upvotes: 0

Views: 292

Answers (1)

Joe
Joe

Reputation: 28376

For your example, you could use updateMany:

db.collection.updateMany({order:{$gte:1}},{$inc:{prevBalance:10, total:10}})

However, to make sure you either change all documents or none, you would probably want to look into multi-document transactions.

Upvotes: 1

Related Questions