使用MongoDB聚合计算两个阵列之间的点积

编程入门 行业动态 更新时间:2024-10-10 16:23:41
本文介绍了使用MongoDB聚合计算两个阵列之间的点积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下格式的文档:

{ '_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聚合计算两个阵列之间的点积

本文发布于:2023-11-22 07:57:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阵列   两个   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!