Mongo $set removing other fields in object on update

2859 views mongodb
3

I am working on a mongo statement for adding and updating values into an object within my document.

Here is my current statement. field and value changes depending what is getting passed in:

 db.collection.update(id, {
   $set: {
     analysis : {[field]: value}
    }
  });

Here is an example of what a document could look like(there are potentially 20+ fields in analysis)

{
 _id
 analysis:{
  interest_rate: 22
  sales_cost: 4000
  value: 300
 }
}

The problem is that every time I update the object all fields are removed except the the field I updated.

so if

field = interest_rate

and the new

value = 33

my document would end up looking like this and all the other fields in analysis would be removed:

 {
   _id
   analysis:{
    interest_rate: 33
   }
  }

Is there a way to update fields within an object like this to keep the code simple or will I have to write out update statements for each individual field?

answered question

1 Answer

2

You should use the dot notation to build the path when you're trying to update nested field. Try:

let fieldPath = 'analysis.' + field; // for instance "analysis.interest_rate"

db.collection.update(id, {
    $set: {
        fieldPath: value
    }
});

Otherwise you're just replacing existing analysis object

posted this

Have an answer?

JD

Please login first before posting an answer.