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
1 Answer 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.