Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: how to update embeded documents in array

Tags:

mongodb

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]"

like image 926
1gn1ter Avatar asked Nov 07 '11 09:11

1gn1ter


1 Answers

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" } }
 )
like image 124
RameshVel Avatar answered Sep 28 '22 06:09

RameshVel