3

I am having the following collection:

{
    "price" : [ 
        55800000, 
        62800000
    ],
    "surface" : [ 
        81.05, 
        97.4
    ],
}

I would want to calculate the price/m2. I have tried the following but got the following error: "$divide only supports numeric types, not array and array".

db.entries.aggregate(
   [
     { $project: { url: 1, pricePerSquareMeter: { $divide: [ "$price", "$surfaces" ] } } }
   ]
)

Would you know how to solve this? Ultimately would want to have an array like this:

{
    "price" : [ 
        55800000, 
        62800000
    ],
    "surface" : [ 
        81.05, 
        97.4
    ],
    "pricePerSquareMeter" : [ 
        688463.91, 
        644763.86
    ]
}

Important: The price and surface should also be ordered so that the calculation is valid.

Goul
  • 573
  • 2
  • 5
  • 16

2 Answers2

1

You can use below aggregation

db.collection.aggregate([
  { "$addFields": {
    "pricePerSquareMeter": {
      "$map": {
        "input": { "$range": [0, { "$size": "$price" }] },
        "in": {
          "$divide": [
            { "$arrayElemAt": ["$price", "$$this"] },
            { "$arrayElemAt": ["$surface", "$$this"] }
          ]
        }
      }
    }
  }}
])

MongoPlayground

Ashh
  • 44,693
  • 14
  • 105
  • 132
  • Thanks a lot, that's really good. How would it be possible to handle the case when the price and surface are not in the right order? ie. that it should be ordered in ascending order in both surface and price before running the calculation. Thank you. – Goul Sep 07 '19 at 14:43
  • @Goul Do you mean **"when both the arrays have different sizes"?** In that case you will have to tell us "what to do" – Ashh Sep 10 '19 at 06:43
1

You can use below aggregation

db.entries.aggregate([
 { $addFields: {
    pricePerSquareMeter: {
       $map: {
         input: '$price',
         as: 'item',
         in: {
            $divide: [
              "$$item", 
               { $arrayElemAt: [ 
                    "$surface", 
                    { "$indexOfArray": ["$price", "$$item"] }
               ]}
            ]
         }
       }
    },
}}])
Ashok
  • 2,846
  • 1
  • 12
  • 20