mongodb - 使用 MongoDB Aggregate 计算两个数组之间的点积

标签 mongodb aggregation-framework

我有以下格式的文档:

{
  '_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在本例中用于生成 4 个元素的数组 (0,1,2,3) 并且这些元素用作 $arrayElemAt 的索引运算符(operator)。 $reduce只是对返回标量值的特定索引的所有乘积求和。 $reduce 中使用了两个特殊变量:$$value 表示 sum,而 $$this 表示 $range< 生成的索引

关于mongodb - 使用 MongoDB Aggregate 计算两个数组之间的点积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50394051/

相关文章:

mongodb - 在 MongoDB 中创建简短、唯一的对象 ID

node.js - 导出mongodb集合数据并使用node js导入回来

mongodb - 将$ graphLookup的ObjectId与String匹配

MongoDb 具有多个分组的聚合管道

performance - Mongodb聚合框架比map/reduce更快吗?

javascript - 使用变量访问嵌套数组中的嵌套对象(MongoDB、Node、Inc)

c - valgrind - 使用 C api 连接到 mongodb 而不会导致 SIGSEGV

mongodb - 如何从 1 分钟嵌套数组数据(mongodb、 Mongoose )聚合 OHLC 5 分钟

MongoDB将数字转换为科学计数法的字符串

mongodb - 在双重嵌套数组 MongoDB 中查找