Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo $set removing other fields in object on update

Tags:

mongodb

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?

like image 704
Kris Avatar asked Nov 07 '18 19:11

Kris


People also ask

How do I remove a field from an object in MongoDB?

The $unset operator deletes a particular field. Consider the following syntax: { $unset: { <field1>: "", ... } } The specified value in the $unset expression (i.e. "" ) does not impact the operation.

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

How do you update an object inside an object in MongoDB?

For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.

How do I update a specific field in MongoDB?

We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.


1 Answers

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.

like image 108
mickl Avatar answered Sep 30 '22 20:09

mickl