如何查找距离给定点一定距离内的所有文档

时间:2017-03-25 19:49:52

标签: mongodb geospatial

给定以下users集合(每个用户可能有多个地址)...

{
    "_id" : ObjectId("58d6c42ba600007001549928"),
    "username" : "user1",
    "firstName" : "Benny",
    "lastName" : "Scott",
    "addresses" : [
        {
            "street": "street 1",
            "houseNr" : "40",
            "zip" : "6949",
            "city" : "Comano",
            "state" : "TI",
            "country" : "Switzerland",
            "timeZone" : "Europe/Zurich",
            "location" : {
                "type" : "Point",
                "coordinates" : [ 8.952682495117188, 46.03413009643555 ]
            }
        }
    ]
},
{
    "_id" : ObjectId("58d6c42ba600007001549930"),
    "username" : "user2",
    "firstName" : "Jonny",
    "lastName" : "Bronson",
    "addresses" : [
        {
            "street": "street 2",
            "houseNr" : "40",
            "zip" : "6949",
            "city" : "Comano",
            "state" : "TI",
            "country" : "Switzerland",
            "timeZone" : "Europe/Zurich",
            "location" : {
                "type" : "Point",
                "coordinates" : [ 8.955499649047852, 46.03577423095703 ]
            }
        },
    ]
}

...如何选择距离给定点不超过20公里的所有用户?

1 个答案:

答案 0 :(得分:0)

...它没有用,因为我忘了创建一个2dsphere索引:

db.users.createIndex( { "addresses.location" : "2dsphere" } )

db.users.find(
   {
     "addresses.location":
       { "$near" :
          {
            "$geometry": { type: "Point", "coordinates" : [ 8.952682495117188, 46.03413009643555 ] },
            "$maxDistance": 20000
          }
       }
   }
)

现在它有效......我希望它有所帮助。