Search code examples
mongodbgroup-byembedded-database

MongoDB group elements in an array


I want, for each product_id, the sum of prices in all orders and another result that I want to achieve is the sum of the price for products in the same array an same id.

\\orders collection:
{
order_id: 123,
customer_id: 1,
order_items: [{product_id:1, price: 2}, {product: 4, price: 8}, {product_id:1, price: 2}]
},
{
order_id: 124,
customer_id: 5,
order_items: [{product_id:5, price: 7}, {product: 4, price: 8}]
}

FIRST result I want:

{product_id: 1, tot_price: 4}, 
{product_id: 4, tot_price: 16},
{product_id: 5, tot_price: 7}

SECOND result:

{order_id:123,
product_tot: [{product_id:1, tot_price: 4}, {product: 4, tot_price: 8}]},
{order_id:124,
product_tot: [{product_id:5, tot_price: 7}, {product: 4, tot_price: 8}},

Solution

  • Try the below queries:

    For 1st Result:

    db.collection.aggregate([
      {
        $unwind: {
          path: "$order_items",
          preserveNullAndEmptyArrays: true
        }
      },
      {
        $group: {
          _id: "$order_items.product_id",
          tot_price: {
            $sum: "$order_items.price"
          }
        }
      },
      {
        $project: {
          _id: 0,
          product_id: "$_id",
          tot_price: 1
        }
      }
    ])
    

    MongoPlayGroundLink

    For 2nd Result:

    db.collection.aggregate([
      {
        $unwind: {
          path: "$order_items",
          preserveNullAndEmptyArrays: true
        }
      },
      {
        $group: {
          _id: {
            order_id: "$order_id",
            product_id: "$order_items.product_id"
          },
          tot_price: {
            $sum: "$order_items.price"
          }
        }
      },
      {
        $project: {
          _id: 0,
          order_id: "$_id.order_id",
          product_id: "$_id.product_id",
          tot_price: "$tot_price"
        }
      },
      {
        $group: {
          _id: "$order_id",
          product_tot: {
            $push: {
              product_id: "$product_id",
              tot_price: "$tot_price"
            }
          }
        }
      },
      {
        $project: {
          _id: 0,
          order_id: "$_id",
          product_tot: 1
        }
      }
    ])
    

    MongoPlayGroundLink