使用MongoDB聚合计算两个阵列之间的点积 [英] Calculate Dot Product between two arrays with MongoDB Aggregate
问题描述
我有以下格式的文档:
{
'_id': ObjectId('5a7884437443cfd470893efc'),
'source': [1,2,3,3]
'sink': [5,6,7,8]
}
如何使用聚合管道计算源阵列和接收器阵列(向量)之间的点积
How can I calculate the dot product between the source and sink arrays (vectors) using the aggregation pipeline
推荐答案
假定两个数组的长度相同,您可以在聚合以下使用:
Assuming both arrays have the same length you can use below aggregation:
db.collection.aggregate([
{
$project: {
dotProduct: {
$reduce: {
input: { $range: [ 0, { $size: "$source" }] },
initialValue: 0,
in: { $add: [ "$$value", { $multiply: [ { $arrayElemAt: [ "$source", "$$this" ] }, { $arrayElemAt: [ "$sink", "$$this" ] } ] } ] }
}
}
}
}
])
$ range 用于生成4的数组在这种情况下,元素(0,1,2,3)
用作 $ arrayElemAt 运算符. $ reduce 只是对返回标量值的特定索引的所有乘积求和. $reduce
中使用了两个特殊变量:$$value
表示和,而$$this
表示由$range
$range is used to generate an array of 4 elements in this case (0,1,2,3)
and those are used as indexes for $arrayElemAt operator. $reduce simply sums all products for particular indexes returning scalar value. There are two special variables used in $reduce
: $$value
represents sum while $$this
represents index generated by $range
这篇关于使用MongoDB聚合计算两个阵列之间的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!