Sriram prasanth
Sriram prasanth

Reputation: 3

I have a Document in mongodb where total_units need to updated by the sum of units present in sub document

  {
    product: "mobile",
    total_units: 10,
    list: [
      {
        "brand": "samsung",
        "units": 5
      },
      {
        "brand": "apple",
        "units": 5
      }
    ]
  }

I need to update total_units based on the units present in the array of sub-documents

I figured out how to update get the total_sum but not how to update the total_sum in the document

db.example3.aggregate({$project: { "result":{$sum: "$list.units"}}})

but how to update in the document

db.example3.update({},{"$set":{"total_units":{"$sum":"$list.units"}}})

the excepted result should be if the brand:apple has the units of 7 and brand samsung has value of 5 the the total units section should be total_units:12

Upvotes: 0

Views: 49

Answers (1)

Naveen
Naveen

Reputation: 246

[email protected]
Add aggregation pipeline to your query. In your case you missed brackets https://mongoplayground.net/p/TgjZUC-jlG_

db.collection.update({},
[
  {
    "$set": {
      "SizeOfList": {
        $size: "$list"
      },
      "total_units": {
        $sum: "$list.units"
      }
    }
  }
])

output

//outputs
[
  {
    "SizeOfList": 2,
    "_id": ObjectId("5a934e000102030405000000"),
    "list": [
      {
        "brand": "samsung",
        "units": 5
      },
      {
        "brand": "apple",
        "units": 5
      }
    ],
    "product": "mobile",
    "total_units": 10
  }
]

Upvotes: 0

Related Questions