$geoNear matching nearest array

让人想犯罪 __ 提交于 2019-11-30 22:06:38

Firstly I strongly advise that you create a "2dsphere" index for your collection if you intend to to geospatial queries on real world coordinates.

Make sure to drop other indexes you may have been playing with:

db.records.dropIndexes();
db.records.createIndex({ "addresses.loc": "2dsphere" })

In order to do what you want, first take a look at the slight modification that also includes the includeLocs option to $geoNear

db.records.aggregate([
  { "$geoNear": {
     "near": [ -73.9815103, 40.7475731 ],
     "spherical": true,
     "distanceField": "distance",
     "includeLocs": "locs"
  }}
])

Now you will see output that looks like this:

{
        "_id" : ObjectId("592d0c78555a7436b0883960"),
        "userid" : 7,
        "addresses" : [
                {
                        "apporx" : 50,
                        "loc" : [
                                -73.98137109999999,
                                40.7476039
                        ]
                },
                {
                        "apporx" : 15,
                        "loc" : [
                                -73.982002,
                                40.74767
                        ]
                },
                {
                        "apporx" : 10,
                        "loc" : [
                                -73.9819567,
                                40.7471609
                        ]
                }
        ],
        "distance" : 0.0000019174641401278624,
        "locs" : [
                -73.98137109999999,
                40.7476039
        ]
}

So what that returned was not only the distance to the point that was nearest but "which" location was the match used.

So if you wanted to $filter the original array to return the nearest, then you can:

db.records.aggregate([
  { "$geoNear": {
     "near": [ -73.9815103, 40.7475731 ],
     "spherical": true,
     "distanceField": "distance",
     "includeLocs": "locs"
  }},
  { "$addFields": {
    "addresses": {
      "$filter": {
        "input": "$addresses",
        "as": "address",
        "cond": { "$eq": [ "$$address.loc", "$locs" ] }
      }
    }
  }}
])

And that returns the array with only that match:

{
        "_id" : ObjectId("592d0c78555a7436b0883960"),
        "userid" : 7,
        "addresses" : [
                {
                        "apporx" : 50,
                        "loc" : [
                                -73.98137109999999,
                                40.7476039
                        ]
                }
        ],
        "distance" : 0.0000019174641401278624,
        "locs" : [
                -73.98137109999999,
                40.7476039
        ]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!