0

I am new to MongoDB and I have the following documents:


{
    "_id":ObjectID("55b89409b7d7df8c3d201618"),  
    "name":"John" 
}, 
{ 
    "_id":ObjectID("55b14359b7d7df8c3d20161c"), 
    "name":"Bahubali",  
    "products":7,  
    "contact_no":8819936800 
}

I need to edit the document which has the name "John". I need to add more fields to this document. But, when I use update, it can update only the specific name field and when I use save, it replaces the existing document with new document.

Is there any other approach to add new fields to the above document without using save. Because whenever we use save, we will require to rewrite the whole document.

bagrat
  • 7,158
  • 6
  • 29
  • 47
ginu
  • 11
  • 1
  • 1
  • possible duplicate of [Add new field to a collection in MongoDB](http://stackoverflow.com/questions/7714216/add-new-field-to-a-collection-in-mongodb) – Neo-coder Jul 29 '15 at 11:55

2 Answers2

3

You can use the $set operator for it:

Example:

db.products.update(
   { name: "John" },
   { $set:
      {
        quantity: 500,
        details: { model: "14Q3", make: "xyz" },
        tags: [ "coats", "outerwear", "clothing" ]
      }
   }
)
bagrat
  • 7,158
  • 6
  • 29
  • 47
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
  • 2
    Edit this to be relevant to the information asked in the question and I'll give you a smiley stamp for your effort. Explain why it is better and two smiley stamps – Blakes Seven Jul 29 '15 at 11:47
0

Try this in your mongoShell.

db.yourCollection.updateMany({"name":"john"}, {$set:{"products":7, "contact_no":8819936800}})
Artaghal
  • 21
  • 5