这实际上只是一道数学题。
考虑一组带有这些 x,y 坐标的构建文档:
var r = [
{_id:1, x:7, y:11}
,{_id:2, x:15, y:10}
,{_id:3, x:10, y:9}
,{_id:4, x:1, y:8}
,{_id:5, x:3, y:7}
,{_id:6, x:16, y:5}
,{_id:7, x:4, y:3}
,{_id:8, x:7, y:3}
,{_id:9, x:6, y:1}
,{_id:10, x:21, y:1}
];
一个按钮被点击并产生点6,5:
var P = {x:6, y:5};
要找到最近的建筑物,只需使用勾股定理迭代并计算距离:
db.foo.aggregate([
// Don't have to worry about absolute value of x-x1 thanks to
// pow(2) making it positive
// dist = sqrt((x-x1)^2 + (y-y1)^2)
{$addFields: {dist: {$sqrt: {$add:[{$pow:[{$subtract:['$x',P.x]},2]}, {$pow:[{$subtract:['$y',P.y]},2]}]}} }},
{$sort: {'dist':1}},
{$limit: 1}
]);
{ "_id" : 8, "x" : 7, "y" : 3, "dist" : 2.23606797749979 }
删除$limit 或将其更改为更大的数字以查看下一个最近的建筑物。