MongoDB BulkWrite update operation $set not working

Hi @Shanka_Somasiri, I am not sure about what you are trying. Here is how you do the update using Aggregation Pipeline, for example.

I have an input document:

{
   _id: 1,
   reservations: [ ]
}

Here is a document I want to push into the reservations array.

var docToUpdate = { loadingShetId: 12, reservedCaseQty: 200 }

The update query:

db.test.updateOne(
  { _id: 1 },
  [
    {
         $set: {
             reservations: {
                 $concatArrays: [ "$reservations", [ docToUpdate ] ]
             }
         }
    }
  ]
)

The updated document:

{
        "_id" : 1,
        "reservations" : [
                {
                        "loadingShetId" : 12,
                        "reservedCaseQty" : 200
                }
        ]
}


The remaining field updates:

$inc: { totalQuantity: -el.loadingTotal }
$set: { currentQuantity: "$totalQuantity" }

Can be coded as follows:

totalQuantity: { $add: [ "$totalQuantity", -el.loadingTotal ] }
currentQuantity: "$totalQuantity"

So, the update query will become:

db.test.updateOne(
  { _id: 1 },
  [
    {
         $set: {
             reservations: {
                 $concatArrays: [ "$reservations", [ docToUpdate ] ]
             },
             totalQuantity: { $add: [ "$totalQuantity", -el.loadingTotal ] },
             currentQuantity: "$totalQuantity"
         }
    }
  ]
)
1 Like