0

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?

1
  • What have you attempted? Please share any code in text with your attempts and the specific error you are obtaining, also I suggest reading how to ask? Commented Mar 24, 2020 at 20:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! That is exactly what I was searching for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.