在 $and 中使用 MongoDB $near
Use MongoDB $near within $and
我正在尝试搜索 "Places",它们靠近某个位置并且满足其他一些条件,如下所示:
var places = Places.find(
{
$and :
[
{ categories : placesCategory },
{
$or :
[
{ name : { $regex : searchQuery, $options : 'i' } },
{ city : { $regex : searchQuery, $options : 'i' } },
{ country : { $regex : searchQuery, $options : 'i' } }
]
},
{
location :
{
$near : [ nearLng, nearLat ],
$maxDistance : 67.15 // radians
}
}
]
}).fetch();
但是控制台告诉我“$near 不能在另一个 $ 运算符内”。
有没有办法将 $near 包含在 $and 中?
或者最佳做法是什么?
您不需要在 $and 语句中包含 $near 查询。你可以把它放在外面,它仍然可以工作。
var places = Places.find(
{
location :
{
$near : [ nearLng, nearLat ],
$maxDistance : 67.15 // radians
},
$and :
[
{ categories : placesCategory },
{
$or :
[
{ name : { $regex : searchQuery, $options : 'i' } },
{ city : { $regex : searchQuery, $options : 'i' } },
{ country : { $regex : searchQuery, $options : 'i' } }
]
}
]
}).fetch();
但是我不确定您的 $near 查询是否正常工作。我更喜欢在坐标上使用 in '2dsphere' 的更具体的查询。例如:
location:
{
$near:
{
$geometry:
{
type: 'Point',
coordinates: [ nearLng, nearLat ]
},
$maxDistance: 67.15 // radians
}
}
编辑:为了使用上述查询,请确保您根据此模型保存数据:
location: {
type: {
type: String,
enum: 'Point',
default: 'Point'
},
coordinates: {
type: [Number],
default: [0,0],
index: '2dsphere'
}
}
当您想在矩形内查找位置时,您可能需要 $box 运算符。这是一个示例搜索查询(请注意,我对此没有经验。您可能需要更改模型and/or 添加索引以改进查询):
location: {
$geoWithin: {
$box: [
[ <bottom left coordinates> ],
[ <upper right coordinates> ]
]
}
}
}
如果有帮助请告诉我!
我正在尝试搜索 "Places",它们靠近某个位置并且满足其他一些条件,如下所示:
var places = Places.find(
{
$and :
[
{ categories : placesCategory },
{
$or :
[
{ name : { $regex : searchQuery, $options : 'i' } },
{ city : { $regex : searchQuery, $options : 'i' } },
{ country : { $regex : searchQuery, $options : 'i' } }
]
},
{
location :
{
$near : [ nearLng, nearLat ],
$maxDistance : 67.15 // radians
}
}
]
}).fetch();
但是控制台告诉我“$near 不能在另一个 $ 运算符内”。
有没有办法将 $near 包含在 $and 中?
或者最佳做法是什么?
您不需要在 $and 语句中包含 $near 查询。你可以把它放在外面,它仍然可以工作。
var places = Places.find(
{
location :
{
$near : [ nearLng, nearLat ],
$maxDistance : 67.15 // radians
},
$and :
[
{ categories : placesCategory },
{
$or :
[
{ name : { $regex : searchQuery, $options : 'i' } },
{ city : { $regex : searchQuery, $options : 'i' } },
{ country : { $regex : searchQuery, $options : 'i' } }
]
}
]
}).fetch();
但是我不确定您的 $near 查询是否正常工作。我更喜欢在坐标上使用 in '2dsphere' 的更具体的查询。例如:
location:
{
$near:
{
$geometry:
{
type: 'Point',
coordinates: [ nearLng, nearLat ]
},
$maxDistance: 67.15 // radians
}
}
编辑:为了使用上述查询,请确保您根据此模型保存数据:
location: {
type: {
type: String,
enum: 'Point',
default: 'Point'
},
coordinates: {
type: [Number],
default: [0,0],
index: '2dsphere'
}
}
当您想在矩形内查找位置时,您可能需要 $box 运算符。这是一个示例搜索查询(请注意,我对此没有经验。您可能需要更改模型and/or 添加索引以改进查询):
location: {
$geoWithin: {
$box: [
[ <bottom left coordinates> ],
[ <upper right coordinates> ]
]
}
}
}
如果有帮助请告诉我!