arrays - 使用 MongoDB 查找最相似的数组
问题描述
我正在尝试使用 MongoDB 查询找到数字数组之间的最小距离。我的技术栈是 Node.js+Mongoose 和 MongoDB 4。
这是我们的输入数组 A:
A = [1, 2, 3, 4, 5]
存储在 MongoDB 中,我们有这样的对象:
[
{
id: 0
nums: [4, 5, 6, 7, 8]
},
{
id: 1
nums: [-500, 50.2, 60, 74, 1]
},
{
id: 2
nums: [9, 5, 32, -7, 5]
}
]
我要做的是使用欧几里得距离公式对对象进行排序。例如,如果我们想在 Mongo 中比较数组 A 和 id:0,我想应用欧几里得距离公式:
distance = Math.sqrt((a1-b1)^2 + (a2-b2)^2 + ... + (an-bn)^2)
在我们的例子中:
x = Math.sqrt((1-4)^2 + (2-5)^2 + (3-6)^2 + (4-7)^2 + (5-8)^2)
我想为x
数据库中的每个数组查找,然后按最小值排序x
。换句话说,我想找到与我们的输入最相似的数组。
我以前在 MongoDB 中写过一些基本查询,但我真的不知道如何解决这类问题。任何帮助将不胜感激。
解决方案
You can start with $zip to "pair" your input array with nums
. Then you can run $reduce to calculate Euclidean formula:
db.collection.aggregate([
{
$addFields: {
distance: {
$let: {
vars: {
pow: {
$reduce: {
input: { $zip: { inputs: [ [1, 2, 3, 4, 5], "$nums" ] } },
initialValue: 0,
in: {
$add: [
"$$value",
{ $pow: [
{ $subtract: [ { $arrayElemAt: [ "$$this", 0 ] }, { $arrayElemAt: [ "$$this", 1 ] } ] } , 2 ] }
]
}
}
}
},
in: { $sqrt: "$$pow" }
}
}
}
},
{
$sort: { distance: 1 }
}
])
推荐阅读
- php - 由于 HTML,PHP 联系表单未发送邮件
- java - Java - 在 JTextArea 中显示来自数据库的信息
- c# - 报告查看器 - 正常模式与打印预览模式不同
- javascript - Angular 材质风格旧时选择器/数字选择器
- tfs - 微软 TFS 研究
- javascript - 对于 javascript 的数组,为什么 [1] ==[1] 返回 false?
- python - 如何有效地从网站搜索功能返回的分页链接列表中抓取页面结果
- bash - 如何使用 bitbucket 管道和分支实现语义版本控制?
- r - 避免在 ggplot2 中按字母顺序重新排序图例
- r - 按行名计算列均值