0

I am trying to figure out how to update the fields nested in a child object within a document in mongodb, there doesnt seem to be a way to do it. Here's what I have.

This is an object. I want to update the fields description, amount and approved attributes

{
 "_id": "...",
 "transaction": {
 "amount": 1,
 "description": "Birthday Money",
 "approved": false,
 "child_id": "...",
 "user_id": "...",
 "_id": "..."
 }
}

I've tried pretty much everything using the $set, but most things will overwrite all fields in the transaction object except for the updated ones or set onto the main document (outside transaction).

I have an object data = { amount: 11, description: "new desc", approved: true }

how can I use the $set update object to update these fields and not destroying the other nested fields

asked Apr 2, 2015 at 20:35

1 Answer 1

1

Use dot notation:

db.test.update(
 {_id: '...'},
 {$set: {
 'transaction.amount' : 44,
 'transaction.approved' : true,
 'transaction.description': 'new stuff'
 }}
)

Do not forget multi if you want update many things.

answered Apr 2, 2015 at 20:39
Sign up to request clarification or add additional context in comments.

2 Comments

Is there no other way of doing it? I may include some or all of those attributes.
@kschieck What is wrong with this way? You can include only one attribute, or as many as you need. Also you can update fields not in transaction field as well.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.