如何根据位置动态过滤数据集
How to dynamically filter datasets based on their location
我正在尝试通过 mongodb 查询实现以下行为:
- 我的文档有一个字段
location
和该字段的 2dshere 地理空间索引
- 文档还有一个字段
maxdistance
- 用户的位置在变量
user.gps
中作为 GeoJSON 点可用
查询当前如下所示:
query["location"] = {
$nearSphere: {
$geometry: user.gps,
$maxDistance: filterDistance
}
};
此查询成功 selects 与用户相关的给定 filterDistance
中的所有数据集。
我现在想要的是"If document.maxdistance
field > 0 and the distance to the user is greater than document.maxdistance
"不要select数据集。
所以如果用户居住的距离大于保存的给定距离在文档中,我有一些文档不应该被找到。
我不知道如何在 mongodb 查询中表达这一点,而且我找不到此类查询的任何示例。
$near/$nearSphere 不支持每个文档的距离。仅针对每个查询。主要原因是按距离排序。如果您只需要过滤,您可以使用 $geoIntersects/$geoWithin,但您需要更改文档以包含覆盖区域的多边形,例如围绕其位置的圆 Pi*2*distance
。
示例:
假设您有一个文档:
{
loc: { type: "Point", coordinates: [ 10, 20 ] },
distance: 10
}
以便当用户的坐标在半径内时返回,例如[12, 25]
,当用户坐标在外面时不返回,例如[12,30]
.
为此,应更新文档以将 loc/distance
对转换为多边形。为了简单起见,我将使用八边形,但您可能希望增加顶点数以获得更准确的结果:
{
loc: { type: "Point", coordinates: [ 10, 20 ] },
distance: 10,
area: {
type : "Polygon",
coordinates : [[
[ 17, 27 ],
[ 10, 30 ],
[ 3, 27 ],
[ 0, 20 ],
[ 3, 13 ],
[ 10, 10 ],
[ 17, 13 ],
[ 20, 20 ],
[ 17, 27 ]
]]
}
}
然后你可以使用$geoIntersects查找包含用户坐标的区域的文档:
db.collection.find({
area: {
$geoIntersects: {
$geometry: { type: "Point" , coordinates: [ 12, 25] }
}
}
})
我正在尝试通过 mongodb 查询实现以下行为:
- 我的文档有一个字段
location
和该字段的 2dshere 地理空间索引 - 文档还有一个字段
maxdistance
- 用户的位置在变量
user.gps
中作为 GeoJSON 点可用
查询当前如下所示:
query["location"] = {
$nearSphere: {
$geometry: user.gps,
$maxDistance: filterDistance
}
};
此查询成功 selects 与用户相关的给定 filterDistance
中的所有数据集。
我现在想要的是"If document.maxdistance
field > 0 and the distance to the user is greater than document.maxdistance
"不要select数据集。
所以如果用户居住的距离大于保存的给定距离在文档中,我有一些文档不应该被找到。
我不知道如何在 mongodb 查询中表达这一点,而且我找不到此类查询的任何示例。
$near/$nearSphere 不支持每个文档的距离。仅针对每个查询。主要原因是按距离排序。如果您只需要过滤,您可以使用 $geoIntersects/$geoWithin,但您需要更改文档以包含覆盖区域的多边形,例如围绕其位置的圆 Pi*2*distance
。
示例:
假设您有一个文档:
{
loc: { type: "Point", coordinates: [ 10, 20 ] },
distance: 10
}
以便当用户的坐标在半径内时返回,例如[12, 25]
,当用户坐标在外面时不返回,例如[12,30]
.
为此,应更新文档以将 loc/distance
对转换为多边形。为了简单起见,我将使用八边形,但您可能希望增加顶点数以获得更准确的结果:
{
loc: { type: "Point", coordinates: [ 10, 20 ] },
distance: 10,
area: {
type : "Polygon",
coordinates : [[
[ 17, 27 ],
[ 10, 30 ],
[ 3, 27 ],
[ 0, 20 ],
[ 3, 13 ],
[ 10, 10 ],
[ 17, 13 ],
[ 20, 20 ],
[ 17, 27 ]
]]
}
}
然后你可以使用$geoIntersects查找包含用户坐标的区域的文档:
db.collection.find({
area: {
$geoIntersects: {
$geometry: { type: "Point" , coordinates: [ 12, 25] }
}
}
})