mongodb update and $set overwrites the document

2.8k Views Asked by At

assume I have a document as;

{
  id: 1,
  name: alex, 
  age: 39,
  surname: felix
  address: [
   { 
     type: "home"
     street: "blabla"
   }
  ]
}

When I wrote the query as;

db.collection.update({id: 1 , adress.type: "home"} ,  { $set : {adress: { street: "test"}});

It changes the document as;

{
  id: 1,
  adress: [
      street: test
  ]
}

However I just want to set the part of the document, just want to change the street name but this query overwrites the document.

How can I edit the partial part of the document in mongodb with update?

2

There are 2 best solutions below

2
On BEST ANSWER

You can try this

db.collection.update( 
  { id: 1, "address.type" : "home" } , 
  {$set : {"address.$.street" : "test"}}
);

Read more from Docs

0
On

Updating items at a position in an array can be done using the positional $ operator

db.collection.update( 
    {id: 1 , adress.type: "home"}, 
    { $set: { "adress.$.street": "test" } }
)

!Note, this only works when ONE (1) sub-document is found