1

For an instance I have a json document in mongodb

{
a:{b:c}
}

Now what am I suppost to do if I want to add to a nested json which will make it look like:

{
a:{b:c, d:e}
}

I have read the documentation of update. It has documented about $inc, $rename, $set & $unset. But I want it to add with existing elements of a. just like $addToSet do with an array.

1 Answer 1

2

You can use the $set operator:

collection.update({'a.b': 'c' }, {$set: {'a.d': 'e'}} )
Sign up to request clarification or add additional context in comments.

3 Comments

for one or two elements its ok! But what will we do when the document will get bigger? :(
@sadaf2605: You can add multiple criteria fields (e.g. if you also needed to match a value for a.f), and likewise for adding additional fields to $set. { $set: {'a.d': 'e', 'a.f': 'g'}} is perfectly legal syntax.
Thank you! :) I was thinking in a complicated way :(

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.