0

I am trying to change an element object that is within an array in a document on Robo3T.

The structure looks like this:

  {
    "_id" : ObjectId("1234"),
    "source" : "BW",
    "sourceTableName" : "lwtrmls",
    "tableName" : "tier",
    "type" : "main",
    "primaryKeys" : [ 
        {
            "sourceField" : "tier_id", // <~~~~ This is what I am trying to update!
            "reportingField" : "bw_id",
            "type" : "integer"
        }
    ]
}

Basically trying to change tier_id under primaryKeys and sourceField to trmls_id.

I have tried something like db.my_collection.update( {_id : "1234"}, {$set : {"primaryKeys.0.tier_id" : "trmls_id"}} ) and that does not seem to be working. Is there a clean way to do this?

BluePilot
  • 373
  • 3
  • 15
  • Does this answer your question? [How to update objects in array in Mongo](https://stackoverflow.com/questions/20668875/how-to-update-objects-in-array-in-mongo) – turivishal Aug 13 '20 at 19:07
  • If primary keys contains more than one object? What should be the condition – Gibbs Aug 13 '20 at 19:13

1 Answers1

1

Basically you need to use $(update)

In you case you need to execute current query:

db.my_collection.update( {_id : "1234", "primaryKeys.sourceField":"tier_id"}, {$set : {"primaryKeys.$.sourceField" : "trmls_id"}} )

Updated:

If you want to update not only first element in array for current filters, but all, you could use $[]

db.my_collection.update( {_id : "1234", "primaryKeys.sourceField":"tier_id"}, {$set : {"primaryKeys.$[].sourceField" : "trmls_id"}, { multi: true }} )
  • updates all not matching fields also, This is not the way to update, it requires arrayFilters and this is duplicate question. answers are already in above comment link. – turivishal Aug 14 '20 at 10:13