Use $multiply on nested fields in aggregation in MongoDB
<p>I am trying to aggregate in MongoDB.</p>

<p>I have a collection with some items. Each item has an array <code>rows</code> and each object in <code>rows</code> has fields <code>quantity</code> and <code>price</code>.</p>

<p>I want to multiply <code>quantity</code> and <code>price</code>, but I don't know how to specify the fields correctly.</p>

<p>I have tried</p>

<pre><code>const pipeline = [
  {
    $group: {
      _id: {
        number: '$number',
      },
      total: {
        $sum: {
          $multiply: [
            '$rows.quantity',
            '$rows.price'
          ]
        }
      },
    }
  }
];
</code></pre>

<p>but it says that <code>$multiply</code> only supports numeric types and not arrays.</p>

<p>So it seems it doesn't understand that <code>$rows.quantity</code> is the numeric type field <code>quantity</code> in each object in the array.</p>

<p>I guess I should probably use <code>$each</code> or something else in order to iterate through the objects in the array.</p>

<p>From <a href="https://stackoverflow.com/questions/16221972/using-multiply-aggregation-with-mongodb">Using multiply aggregation with MongoDB</a> I see that I am specifying the fields correctly; however, in that example it is a nested object instead of an array, so maybe I have to use <a href="https://docs.mongodb.org/v3.0/reference/operator/aggregation/unwind/" rel="nofollow noreferrer">https://docs.mongodb.org/v3.0/reference/operator/aggregation/unwind/</a>?</p>

<h1>Sample document</h1>

<pre><code>{
  number: 2,
  rows: [
    {
      quantity: 10,
      price: 312
    },
    {
      quantity: 10,
      price: 312
    },
    {
      quantity: 10,
      price: 312
    },
  ]
}
</code></pre>