Samuel Mariña
Samuel Mariña

Reputation: 129

How to sum all the values in an array in mongodb?

I have this document

{
    "_id" : ObjectId("5e7948fc9a0d0e5ca78aa886"),
    "product_id" : ObjectId("5e76c896eebef71b39aa8277"),
    "user_qty" : [
        {
            "user_id" : ObjectId("5e76c997eebef71b39aa827a"),
            "qty" : 20
        },
        {
            "user_id" : ObjectId("5e794aa19a0d0e5ca78aa887"),
            "qty" : 40
        }
    ],
    "price" : 20,
    "reviews" : [
        {
            "name" : "Pablo Perez",
            "comment" : "Me quedan muy bien!"
        },
        {
            "name" : "Corina Smith",
            "comment" : "Muy nice"
        }
    ],
    "location" : {
        "street" : "La Bonita",
        "city" : "Caracas",
        "country" : "Venezuela"
    }
}

I would like to make a query that returns the sum of all the quantities (qty) in the array user_qty. In this document, it would be 20 + 40 = 60. Any help?

Upvotes: 0

Views: 33

Answers (1)

matthPen
matthPen

Reputation: 4343

You can use aggregation framework to achieve this quite simply.

db.collection.aggregate([
  {
    $addFields: {
      totalQty: {
        $sum: "$user_qty.qty"
      }
    }
  }
])

If you need only total (and not original fields), replace $addFields by $project

Try it here

Upvotes: 1

Related Questions