How to create a field that contains values formulated with values of other fields?

Hii :wave:
I have a collection orders, containing a field total_item. Total Items are calculated with sumation of all numerical values present in item. Item is present in list of object.

For example:

total_item: 10,
listOfItems:[
{ item: 5, name: "Value1"}, 
{ item: 3, name: "Value2"}, 
{ item: 2, name: "Value3"}
]

Now lets say that if a new item comes in listOfItems then the value of total_item should automatically update.
For example:
if my new value is { item: 5, name: “Value4”}
Then expected update in my collection should be:

total_item: 15,
listOfItems:[
{ item: 5, name: "Value1"}, 
{ item: 3, name: "Value2"}, 
{ item: 2, name: "Value3"},
{ item: 5, name: "Value4"}
]

Is there any way to create this kind of flow?
Because its only an example, but in my collection it contains multiple fields which are based on multiple numerical calculations and its hard to track correct data inserted through every formula.

This is just like formula field in SalesForce.

Hope this information is helpful to solve my query :smiling_face:

Try the following untested code.

Assuming document:

_id : 1 ,
total_item: 10,
listOfItems:[
{ item: 5, name: "Value1"}, 
{ item: 3, name: "Value2"}, 
{ item: 2, name: "Value3"}
]
new_value = { "item" : 5 , "name" : "value4" } ;

query = { "_id" : 1 } ;

update = {
    "$inc" : { "total_item" :  new_value.item } ,
    "$push" : { "listOfItems" : new_value }
} ;

db.orders.updateOne( query , update ) ;

As reference:

Thanx for your response. But what I want is not update query. My requirement is that field should be enough efficient to automatically calculate the values based on given formula.

Sorry that I misunderstood your question which was:

This looked like you wanted an update operation.

I apologize if my previous explanation was unclear. My concern revolves around the automatic update of the ‘total_item’ value when a new item is inserted into my list, similar to the example provided. How can I achieve this functionality in MongoDB?

I am not aware of any “formula” type field in MongoDB. May be mongoose can do it for you.

In plain mongo, you may

  1. update the field like I shared
  2. compute the field with a projection every time you find or aggregate
  3. create a view with the same aggregation as #2 above

#1 is the fastest but takes more space, the computed value can be indexed, it has a high risk of becoming out of sync if documents are manipulated without your API

Okay noted. But this procedure is depended on API, and my documents are manipulated by API itself. So, I think it would better that API code should be properly written.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.