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?

2
  • Does this answer your question? How to update objects in array in Mongo Commented Aug 13, 2020 at 19:07
  • If primary keys contains more than one object? What should be the condition Commented Aug 13, 2020 at 19:13

1 Answer 1

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 }} )
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.