BluePilot
BluePilot

Reputation: 403

Mongo script to update an object if its a certain value

I am trying to update a document in Mongo if it has a certain value within a field.

{
    "_id" : ObjectId("myObject"),
    "source" : "BW",
    "sourceTableName" : "myTable",
    "tableName" : "tier",
    "type" : "main",
    "fieldMappings" : [ 
        {
            "sourceField" : "tier_id", <~~~~ If this is "tier_id", I want to change it to "trmls_id"
            "reportingField" : "bw_id",
            "type" : "integer",
            "defaultMap" : {
                "shouldErrorOnConvert" : false
            }
        }
    ]
}

I tried something like

db.getCollection('entityMap').update({"sourceTableName":"myTable"}, {"fieldMappings.0.sourceField":"trmls_id":{$exists : true}}, { $set: { "fieldMappings.0.sourceField": "tier_id" } })

and I think it is failing on the $exists parameter I am setting.

Is there a more cleaner/dynamic way to do this?

The whole query I am trying to formulate is

  1. In the table myTable
  2. I want to check if there is a sourceField that has the value tier_id
  3. If there is tier_id, then change it to trmls_id
  4. Otherwise do nothing

If there is a similar StackOverflow question that answers this, I am happy to explore it! Thanks!

Upvotes: 1

Views: 384

Answers (1)

turivishal
turivishal

Reputation: 36104

There is a syntax mistake and you can use positional operator $ in update part because you have already selector field in query part,

db.getCollection('entityMap').update(
  { 
      "sourceTableName": "myTable",
      "fieldMappings.sourceField": "tier_id" // if this field found then it will go to update part
  }, 
  {
      $set: {
          "fieldMappings.$.sourceField": "trmls_id"
      }
  }
)

Upvotes: 1

Related Questions