Reputation: 1444
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]"
Upvotes: 6
Views: 7957
Reputation: 65877
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" } }
)
Upvotes: 16