How do I set and unset together with aggregate-update in mongodb?

Viewed 1122
db.getCollection('name').update({"bid":"3860"},
{
    [ 
    {"$set":
        { "tl" :
            { $add : 
                [   
                    {
                      $multiply: ["$intField", 24*60*60*1000]
                    },
                    "$dateField"
                ]
            }
        }
    },
    { "$unset": {'intField' : 1}}
    ]
    
}
}
)

I am able to do $set. I am trying to do $unset also in single call.

is it possible? Mongo Version is 4.2. Any suggestions please?

2 Answers

You are almost there. There is a small mistake that $update aggregation operator accepts either a string or an array.

db.getCollection('name').update({
  "bid": "3860"
},

  [
    {
      "$set": {
        "tl": {
          $add: [
            {
              $multiply: [
                "$intField",
                24*60*60*1000
              ]
            },
            "$dateField"
          ]
        }
      }
    },
    {
      "$unset": 'int2Field' -->change here
    } 
  ]

})

It is not same as $unset update operator syntax. It is $unset aggregate operator format.

Refer

This update with aggregation pipeline will remove the intField field from the document using the REMOVE aggregation system variable:

db.set.update( 
  { },
  [ 
    { 
       $set: { 
         t1: { $add: [ { $multiply: ["$intField", 24*60*60*1000 ] }, "$dateField" ] }, 
         intField: "$$REMOVE" 
       } 
    } 
  ] 
)
Related