我有以下格式的文档:
{
'_id': ObjectId('5a7884437443cfd470893efc'),
'source': [1,2,3,3]
'sink': [5,6,7,8]
}
如何使用聚合管道计算源数组和接收器数组(向量)之间的点积
假设两个数组具有相同的长度,您可以使用以下聚合:
db.collection.aggregate([
{
$project: {
dotProduct: {
$reduce: {
input: { $range: [ 0, { $size: "$source" }] },
initialValue: 0,
in: { $add: [ "$$value", { $multiply: [ { $arrayElemAt: [ "$source", "$$this" ] }, { $arrayElemAt: [ "$sink", "$$this" ] } ] } ] }
}
}
}
}
])
$range https://docs.mongodb.com/manual/reference/operator/aggregation/range/在本例中用于生成 4 个元素的数组(0,1,2,3)
这些被用作索引$arrayElemAt https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/操作员。$reduce https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/只是对返回标量值的特定索引的所有乘积求和。其中使用了两个特殊变量$reduce
: $$value
代表总和,同时$$this
表示生成的索引$range
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)