MongoDB: how to update inline documents in an array

I have the following document:

{_id: '4eb79ee1e60fc603788e7259', Name: 'name', Subsidiaries: [ { _id: '4eb79eeae60fc603788e7271', Location: 'location1'}, { _id: 'subid2', Location: 'location2'}, ]} 

I want to update the child location:

 db.Departments.update({ "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.Location" : "City" } }) 

But MongoDb returns an error: "cannot join the array using the string field name [Location]"

+6
source share
1 answer

You should use the $ poistional operator to update inline documents,

 db.Departments.update( { "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.$.Location" : "City" } } ) 
+15
source

Source: https://habr.com/ru/post/900922/


All Articles