Unset field in array

Hello Everyone,For the below mentioned document,i want to unset the percentage field in cugMasterAccountDetails Array when the percentage is equal to Zero.

{
  "_id": {
    "$oid": "635f63b41c66064760addc11"
  },
  "isMigrated": true,
  "isDeleted": false,
  "createdBy": {
    "userId": 11088,
    "userName": "ANIL64"
  },
  "modifiedBy": {
    "userId": 11088,
    "userName": "ANIL64"
  },
  "cugMasterAccountId": 15,
  "customerId": 10025094,
  "type": " ",
  "cugMasterAccountDetails": [
    {
      "tagAccountNumber": 20056411,
      "vehicleId": 56346,
      "startDate": "2016-10-21 00:00:00",
      "minBalance": 2000,
      "maxBalance": 700,
      "percentage": 0
    },
    {
      "tagAccountNumber": 20056411,
      "vehicleId": 56346,
      "startDate": "2016-10-21 00:00:00",
      "minBalance": 1000,
      "maxBalance": 700,
      "percentage": 0
    }
  ]
}

Hello @Amrutha_Sai_Kala_Challapalli, Welcome to the MongoDB community forum,

You can use the $unset operator to delete fields,

And use filtered positional operator and arrayFilters to match the nested elements by providing condition,

You can try something like this,

  • use your required method if you are updating single document then use updateOne or if you are updating multiple document use updateMany
db.collection.updateMany(
  { "cugMasterAccountDetails.percentage": 0 },
  { $unset: { "cugMasterAccountDetails.$[c].percentage": "" } },
  { arrayFilters: [{ "c.percentage": 0 }] }
)
3 Likes

Thanks for your quick response.I will try it.