Can same field be used in $sert, $unset of update(aggregate)

Viewed 108

I answered this question

I couldn't explain the reason why the same field cannot be used in update(aggregate) in the order of set then unset.

That looks valid to me at first sight. Since aggregation operator[] is mentioned, I believe that $set can use that $intField and then it can $unset.

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

Please help me to understand this.

1 Answers

You can use same field in $set and $unset stages of update aggregation pipeline.

You have a syntax error in your query. Second argument to .update() function should be an array instead of an object. Remove the curly braces around [] and the query will work.

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