1

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.

1

2 Answers 2

4

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" ]
      }
   }
)
Sign up to request clarification or add additional context in comments.

2 Comments

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
Recent versions use updateOne() or updateMany(). Also note $set is an alias for $addFields.
0

Try this in your mongoShell.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.