0
label : {
   field1 : { .....},
   field2 : {.....}
}
db.collection.update({_id:"objectId"},{$set : label})

I have a single collection with multiple fileds and I want to update field1 without removeing field2, is this possible?

For example

{ 
    "_id" : ObjectId("56fa03....."), 
    "categories" : { 
        "category_name" : { 
            "en" : "Category Name", 
            "dk" : "Category Name DK" 
        }, 
        "color" : { "en" : "Color", "dk" : "Color DK" } 
    } 
} 

Here I want to update category_name without removeing color. How do I update a single field1 in a record?

  • 2
    Could you clarify what you're asking? What exactly do you mean by "I want to update field1 without reading field2"? – Joachim Isaksson Mar 29 '16 at 09:22
  • `{ "_id" : ObjectId("56fa03....."), "categories" : { "category_name" : { "en" : "Category Name", "dk" : "Category Name DK" }, "color" : { "en" : "Color", "dk" : "Color DK" } } }` Here i want to update `category_name` without reading `color` .. – Chethan KSwamy Mar 29 '16 at 09:30

1 Answers1

0
db.getCollection('CollectionName')
    .update("_id" : "objectId", 
        {$set : {"label.field1" : "value of field 1"}})

based on documentation(v 3.2) :

The update() method either modifies specific fields in existing documents or replaces an existing document entirely.

To update an embedded document or an array as a whole, specify the replacement value for the field. To update particular fields in an embedded document or in an array, use dot notation to specify the field

.

Community
  • 1
  • 1
Søren
  • 6,517
  • 6
  • 43
  • 47
  • While this code may answer the question, providing additional context regarding _why_ and/or _how_ this code answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Mar 29 '16 at 10:31
  • done. @TobySpeight – Søren Mar 29 '16 at 10:51