如果位置坐标在另一个集合中,我如何使用$near查询服务?
$lookup,$near
我有2个收藏,一个是给用户的,另一个是服务的。
用户集合为:
{ "_id" : ObjectId("570557d4094a4514fc1291d6"), "fullname" : "John Doe",
"position" : {
"street" : "Piazza Santa Maria",
"city" : "Busto",
"country" : "Italy",
"zip_code" : "21052",
"address" : "Piazza Santa Maria, 21052 Busto, Province of Varese, Italy",
"location" : {
"type" : "Point",
"coordinates" : [
8.8502715,
45.6114064
]
},
"country_code" : "IT",
"state" : "Lombardy",
"province" : "Province of Varese"
}
}}
服务集合为:
{ "_id" : ObjectId("960557d4094a4514fc1291a7"),
author_id : ObjectId("570557d4094a4514fc1291d6"), title:"Software developer"}
{ "_id" : ObjectId("960557d4094a4514fc1291a7"),
author_id : ObjectId("570557d4094a4514fc1291d6"), title:"App developer"}我希望根据作者位置查找服务集合中的所有文档。
发布于 2016-10-24 08:44:44
首先,您需要满足基于位置的MongoDB查询的两个需求。
在 collection
$geoNear阶段上创建users 示例:
db.users.aggregate([
{
$geoNear: {
near: {type: "Point", coordinates: [ 8.840 , 45.6114060 ]},
distanceField: "dist.calculated",
maxDistance:1000,
spherical: true
}},
{
$lookup: {
from:"services", localField:"_id", foreignField:"author_id", as: "services"
}}
])在这里,我们试图找到落在1000米范围内的文档。在本例中,文档的位置为[8.8502715, 45.6114064]
输出
{
"_id" : ObjectId("570557d4094a4514fc1291d6"),
"fullname" : "John Doe",
"position" : {
"street" : "Piazza Santa Maria",
"city" : "Busto",
"country" : "Italy",
"zip_code" : "21052",
"address" : "Piazza Santa Maria, 21052 Busto, Province of Varese, Italy",
"location" : {
"type" : "Point",
"coordinates" : [
8.8502715,
45.6114064
]
},
"country_code" : "IT",
"state" : "Lombardy",
"province" : "Province of Varese"
},
"dist" : {
"calculated" : 799.8404739526889
},
"services" : [
{
"_id" : ObjectId("960557d4094a4514fc1291a7"),
"author_id" : ObjectId("570557d4094a4514fc1291d6"),
"title" : "Software developer"
},
{
"_id" : ObjectId("580d499eb22270301913d677"),
"author_id" : ObjectId("570557d4094a4514fc1291d6"),
"title" : "Software developer"
},
{
"_id" : ObjectId("580d499eb22270301913d678"),
"author_id" : ObjectId("570557d4094a4514fc1291d6"),
"title" : "App developer"
}
]
}如果我们在google地图上绘制这两个文档以进行验证,我们将得到

正如您在图像上看到的,我们的文档位置大约相隔800米,因此在query中指定的1000米范围内。请参阅Goole map
https://stackoverflow.com/questions/40208218
复制相似问题