给定以下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公里的所有用户?
答案 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
}
}
}
)
现在它有效......我希望它有所帮助。