Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Mongodb中使用地理空间查询从点数组返回最近的点_Mongodb - Fatal编程技术网

在Mongodb中使用地理空间查询从点数组返回最近的点

在Mongodb中使用地理空间查询从点数组返回最近的点,mongodb,Mongodb,我有一个集合,它有一个geo_json对象数组,如下所示: { id: 1, title: 'test', description: 'test', locations: [ { geo_json: { type: 'Point', coordinates: [121.21, 14.58] } }, { geo_json: {

我有一个集合,它有一个geo_json对象数组,如下所示:

{
   id: 1,
   title: 'test',
   description: 'test',
   locations: [
      {
         geo_json: {
            type: 'Point',
            coordinates: [121.21, 14.58]
         }
      },
      {
         geo_json: {
            type: 'Point',
            coordinates: [111.11, 10.28]
         }
      }
   ]
}
我在该字段上有一个2DSphere索引,我的查询如下所示:

query = {
            'locations.geo_json': {
                '$near': {
                    '$geometry': {
                        'type': 'Point',
                        'coordinates': [lng, lat]
                    },
                    '$maxDistance': 5000
                }
            }
        }
{
   id: 1,
   title: 'test',
   description: 'test',
   locations: [
      {
         geo_json: {
            type: 'Point',
            coordinates: [121.21, 14.58]
         }
      }
   ]
}
它做了应该做的事情,即返回指定半径(最大距离)内的集合项,我的问题是,我只想返回数组中“靠近”指定坐标的实际点,而不是整个位置数组

例如,像上面一样,如果我用
lat=14.58,lng=121.21
进行查询,我将得到id=1的项目,但在locations字段中,我只需要匹配的位置,即
[121.21,14.58]
,不包括
[111.11,10.28]

所以它会像这样返回:

query = {
            'locations.geo_json': {
                '$near': {
                    '$geometry': {
                        'type': 'Point',
                        'coordinates': [lng, lat]
                    },
                    '$maxDistance': 5000
                }
            }
        }
{
   id: 1,
   title: 'test',
   description: 'test',
   locations: [
      {
         geo_json: {
            type: 'Point',
            coordinates: [121.21, 14.58]
         }
      }
   ]
}
这将有助于打印围绕查询点的项目


希望有人能帮上忙:)

您只需要距离半径最近的位置吗?只有一个,如果我没有错的话?@JETHALAL我想你的思路是对的,id为1的文档有两个坐标,一个坐标是最近的,另一个不是。他的查询返回id为1的正确文档,因为它具有最接近的点。但是,由于返回了整个文档,因此它还具有另一个坐标,而该坐标不是最接近的坐标。他只需要具有最近点的过滤文档。您只需要相对于半径的最近位置?只有一个,如果我没有错的话?@JETHALAL我想你的思路是对的,id为1的文档有两个坐标,一个坐标是最近的,另一个不是。他的查询返回id为1的正确文档,因为它具有最接近的点。但是,由于返回了整个文档,因此它还具有另一个坐标,而该坐标不是最接近的坐标。他只希望筛选出最近点的文档。