在$ and之内在$ near附近使用MongoDB [英] Use MongoDB $near within $and
问题描述
我正在尝试搜索位置",该位置靠近某个位置并符合其他条件,如下所示:
I am trying to search "Places", which are near to a Location AND meet some other criteria as seen here:
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();
但是控制台告诉我"$ ear不能在另一个$运算符之内".
However the console tells me that "$near can't be inside another $ operator".
是否可以将$ ear包含在$ and中?
Is there a way to include the $near inside the $and?
或者最佳做法是什么?
推荐答案
您不需要在$ and语句中包含$ near查询.您可以将其放置在外面,否则将无法正常工作.
You don't need to include your $near query inside your $and statement. You can place it outside and it will stil work.
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查询是否正常工作.我更喜欢在坐标上使用'2dsphere'的更具体的查询.例如:
I am however not sure if your $near query is working properly. I prefer a more specific query with an in '2dsphere' on the coordinates. For example:
location:
{
$near:
{
$geometry:
{
type: 'Point',
coordinates: [ nearLng, nearLat ]
},
$maxDistance: 67.15 // radians
}
}
编辑:为了使用上面的查询,请确保您根据此模型保存数据:
EDIT: In order to use the above query, make sure you are saving you data according to this model:
location: {
type: {
type: String,
enum: 'Point',
default: 'Point'
},
coordinates: {
type: [Number],
default: [0,0],
index: '2dsphere'
}
}
当您想在矩形内查找位置时,可能需要 $ box 运算符.这是一个搜索查询示例(请注意,我没有经验.您可能需要更改模型和/或添加索引以改进查询):
When you want to find places inside a rectangle, you wil probably need the $box operator. This is an example search query (please note, I have no experience with it. You might need to change your model and/or add an index to improve the query):
location: {
$geoWithin: {
$box: [
[ <bottom left coordinates> ],
[ <upper right coordinates> ]
]
}
}
}
让我知道这是否有帮助!
Let me know if this helps!
这篇关于在$ and之内在$ near附近使用MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!