0

I have the following collections in my database:

{
    "username" : "John",
    "shopping_cart" : {
        "coffee" : 2,
        "chocolate" : 3
      (...will have about 50 different products that can be added to the shopping cart)
    },
}

Is there a way to aggregate all items that a user had added in the shopping cart and get a total sum of the entire quantity of the cart? Something like this.

db.items.aggregate([
    {$group: {
        _id: null,
        prices: {$sum: "$all_items_in_shopping_cart}
    }}
])
turivishal
  • 34,368
  • 7
  • 36
  • 59
Leo Tsang
  • 27
  • 4

2 Answers2

0

You have 3 different steps

  1. First, convert your object to array

    $project: { shopingItems: { $objectToArray: "$shopping_cart" } }

  2. Unwind your new element

    $unwind: { path: "$shopingItems" }

  3. Group base on id to get the summation

    $group: { _id: "$_id", total: { $sum: "$shopingItems.v" }

Your final query be something like:

db. items. aggregate[
    {    
    '$project': {
      'shopingItems': {
        '$objectToArray': '$shopping_cart'
      }
    }
  }, {
    '$unwind': {
      'path': '$shopingItems'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'total': {
        '$sum': '$shopingItems.v'
      }
    }
  }
]
Ashkan
  • 1,357
  • 4
  • 16
  • 37
0

You an try,

  • $addFields add new field shopping_cart_sum
  • $reduce to input shopping_cart array after converting to array using $objectsToArray, set initialValue to zero, in to add value of object key and value of initialValue using $add
db.items.aggregate([
  {
    $addFields: {
      shopping_cart_sum: {
        $reduce: {
          input: { $objectToArray: "$shopping_cart" },
          initialValue: 0,
          in: { $add: ["$$this.v", "$$value"] }
        }
      }
    }
  }
])

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59