首页 > 解决方案 > 使用 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 中写过一些基本查询,但我真的不知道如何解决这类问题。任何帮助将不胜感激。

标签: arraysnode.jsmongodbaggregation-framework

解决方案


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 }
    }
])

Mongo Playground


推荐阅读