Thursday, 8 June 2017

Mongo - update a field with result of another field when a document is updated

I'm working with mongoose to manage my mongoDB collections. I have one collection that contains two numeric fields. I want to set another field with the result of dividing these two fields every time that one of them is updated.

Let's sat this is my mongo collection:

{
  id: 1,
  num1: 100,
  num2: 50,
  result: 2
},
{
  id: 2,
  num1: 200,
  num2: 10,
  result: 20
},
{
  id: 1,
  num1: 40,
  num2: 5,
  result: 8
}

Now, the item with id 2 is updated, and num1 is set to 50. I want to recalculate and set result field with the new correct value (10).

(for updating items, I use the bulk.find().upsert().updateOne() funciton).

How can I do it with the less performance impact?



via user2717436

No comments:

Post a Comment