Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

Given this document saved in MongoDB

_id : ..., 

some_key: 

param1 : "val1", 

param2 : "val2",

param3 : "val3" 

}

An object with new information on param2 and param3 from the outside world needs to be saved

var new_info = { 

param2 : "val2_new",

param3 : "val3_new" 

};

I want to merge / overlay the new fields over the existing state of the object so that param1 doesn't get removed

Doing this

db.collection.update({ _id:...},{ $set:{ some_key : new_info }}

Will lead to MongoDB is doing exactly as it was asked, and sets some_key to that value. replacing the old one.

_id : ...,

some_key: {

 param2 : "val2_new", 

 param3 : "val3_new" 

}

What is the way to have MongoDB update only new fields (without stating them one by one explicitly)? to get this:

{

_id : ..., 

some_key: { 

param1 : "val1", 

param2 : "val2_new", 

param3 : "val3_new" 

}

I'm using the Java client, but an example will be appreciated

2 Answers

0 votes
by (106k points)

To partially update an object in MongoDB you can do something like as follows:-:

db.collection.update( { _id:...},{ $set: someObjectWithNewData }

0 votes
by (107k points)

You first have to query the document, figure out what you want to $set and then update it (using the old values as a matching filter to make sure you don't get concurrent updates in between).

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...