简体   繁体   English

如何使用聚合将2个数组的对应元素相乘?

[英]How to multiply the corresponding elements of 2 arrays using aggregation?

I want to multiply the individual elements of 2 arrays: 我想乘以2个数组的各个元素:

{
  "lessonHours": [2, 1, 2]
},
{
  "studentCount": [2, 6, 5]
}

I have tried $multiply but since it works only for numeric values and not array. 我已经尝试了$ multiply,但是由于它仅适用于数值而不是数组。

I need something like this: 我需要这样的东西:

{
  "product": [4, 6, 10]
}

First element is 2(1st array)*2(2nd array) = 4. Then 1*6, 2*5 第一个元素是2(1st array)*2(2nd array) = 4. Then 1*6, 2*5

Use .map . 使用.map Don't use .forEach because you'll have to manually push the value back. 不要使用.forEach因为您必须手动将值推回去。

let calculatedValues = lessonHours.map((item, index) => item * studentCount[index])

This is only applicable if both your arrays have the same length. 仅当两个数组的长度相同时才适用。 You'll need to restructure your code if both arrays won't have the same length. 如果两个数组的长度都不相同,则需要重组代码。

You can use below aggregation 您可以使用以下汇总

db.collection.aggregate([
  { "$project": {
    "product": {
      "$map": {
        "input": { "$range": [ 0, { "$size": "$lessonHours" }] },
        "in": {
          "$multiply": [
            { "$arrayElemAt": ["$lessonHours", "$$this"] },
            { "$arrayElemAt": ["$studentCount", "$$this"] }
          ]
        }
      }
    }
  }}
])

Output 产量

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "product": [
      4,
      6,
      10
    ]
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM