Real use of Computed pattern and Approximation pattern

Hello,

I’ve read this article about computed pattern however it is very theoretical I’ve got a hard time to understand how to implement it. Let’s say I have a collection as the one below:

"User": {
    "_id": "<ObjectId>",
    "firstname": "<String>",
    "birthdate": "<ISODate>",
    "inscriptionDate": "<ISODate>",
    "lastConnectionDate": "<ISODate>",
    "totalFriends": "<Int>",
    "totalMessageSent": "<Int>"
}

TotalFriends computed only

For this example let’s exclude the approximation pattern.
totalFriends will be updated every time one user accept or remove a friend. How should I update this field ? Should I do a simple

db.users.update(
    { _id: 1 },
    { $inc:{ totalFriends: 1}}
)

totalMessageSent computed + approximation

For example totalMessageSent will be updated every 10 messages sent. How should I update this field ?

Hi, @Yoni_Obia - welcome to the community!

I’m curious how you ended up implementing this. Did you find an implementation that worked for you? Did you discover anything that didn’t work so well?

For TotalFriends, doing the increment every time a friend is added probably makes sense. Another option would be to calculate the number of friends periodically. My guess is that adding a friend doesn’t happen super frequently, so the $inc approach will likely be the better approach.

For the totalMessagesSent, you could do something like:
{ $inc: { totalMessagesSent: -10 } }