I have the following document:
{_id: '4eb79ee1e60fc603788e7259',
Name: 'name',
Subsidiaries: [
{ _id: '4eb79eeae60fc603788e7271',
Location: 'location1'},
{ _id: 'subid2',
Location: 'location2'},
]}
I want to update subsidiary's location:
db.Departments.update({ "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.Location" : "City" } })
But MongoDb returns an error: "can't append to array using string field name [Location]"
You have to use $ poistional operator to update the embedded documents,
db.Departments.update(
{ "_id" : ObjectId("4eb79ee1e60fc603788e7259"),
"Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") },
{ "$set" : { "Subsidiaries.$.Location" : "City" } }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With