mmu36478
mmu36478

Reputation: 1355

mongodb update and $set overwrites the document

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?

Upvotes: 3

Views: 2925

Answers (2)

Jyothi Babu Araja
Jyothi Babu Araja

Reputation: 10282

You can try this

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

Read more from Docs

Upvotes: 5

digit
digit

Reputation: 4565

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

Upvotes: 0

Related Questions