U
U
Urukhayy2018-05-13 14:50:03
MongoDB
Urukhayy, 2018-05-13 14:50:03

(MVC) Should the sum be stored in the model?

In a Mongo database (JSON storage), the document contains an array of objects:

{
    myArray: [{a: 1}, {a: 2}, {a: 3}, {a: 4}]
}

The application needs to know the sum of all a 's in myArray . Do I need to store this as a property of the model, and update the property when the array changes?
{
    myArray: [{a: 1}, {a: 2}, {a: 3}, {a: 4}],
    sum_a: 10
}

Or do not store the property of the sum and recalculate the sum reactively with each request, running through the array? And if a lot of documents are retrieved, isn't it expensive to count the same thing every time?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2018-05-13
@DmitriyEntelis

There is such a generally correct opinion that any task should be started with SQL and 3rd normal form, and only then, based on the load profile, carefully introduce denormalization and data duplication.
Since you already have Mongo, the advice is generally late, but still applicable here.

And if a lot of documents are retrieved, isn't it expensive to count the same thing every time?
No one except you can measure this in a live project on a live task and compare it with the cost of updating while saving.
In some cases, it is more profitable to consider not flying.
In some cases, it is more profitable to cache and recalculate when changing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question