我有纬度和经度数组,但我无法与整个数组匹配。所以我必须迭代循环并在循环中执行以下单个查询。所以执行查询需要花费很多时间。
我的循环查询
Collection.find({'location':{$near:{$geometry:{type:"point",coordinates:[longitude,latitude]},$maxDistance:20}}}).exec(function(err,res){
});
期待查询
{'location':{$near:{$geometry:{type:"point",coordinates:[[longitude,latitude],[longitude,latitude],[longitude,latitude]]},$maxDistance:20}}}
我有坐标数组但是我不能在这里传递整个数组所以我必须在循环中传递单个纬度和经度。
有没有办法使用坐标数组从数据库中查找数据?
更新
我尝试了以下查询
Collection.find({'location':{$near:{$geometry:{type:"point",coordinates:[[72.502912,23.011787],[ 72.50265, 23.011772 ]]},$maxDistance:20}}});
我收到了以下错误
error: {
"waitedMS" : NumberLong(0),
"ok" : 0,
"errmsg" : "invalid point in geo near query $geometry argument: { type: \"point\", coordinates: [ [ 72.50291199999999, 23.011787 ], [ 72.50265, 23.011772 ] ] } Point must only contain numeric elements",
"code" : 2
}
文档
{
"_id" : ObjectId("5abcf7ae59869428b40c5727"),
"latitude" : 23.8787,
"longitude" : 72.7788,
"location" : [
72.7788,
23.8787
],
"address" : "Ahmedabad",
"status" : "active",
"eventId" : "5a8d6a27733b28295db9635e",
"eventCreateBy" : "admin",
"description" : "",
"isDeleted" : "0",
"createdAt" : ISODate("2018-03-29T14:26:54.198Z"),
"updatedAt" : ISODate("2018-03-29T14:26:54.198Z")
}
坐标
[72.7788,23.8787] : Matched
[72.5032552,23.0122194]: Matched
[18.1519461,43.8984328]: Not Matched
答案 0 :(得分:0)
问题
它无法与$near一起使用。函数按距离对结果进行排序,当查询中有多个$near
运算符时,不清楚返回结果的顺序,因此请求如
db.collection.find({$or: [
{'location':{$near:{$geometry:{type:"point",coordinates:[ 72.50325, 23.01222 ]},$maxDistance:50000}}},
{'location':{$near:{$geometry:{type:"point",coordinates:[ 72.7788, 23.8787 ]},$maxDistance:50000}}}
]});
<{3}}中明确禁止:
// There can only be one NEAR. If there is a NEAR, it must be either the root or the root
// must be an AND and its child must be a NEAR.
size_t numGeoNear = countNodes(root, MatchExpression::GEO_NEAR);
if (numGeoNear > 1) {
return Status(ErrorCodes::BadValue, "Too many geoNear expressions");
}
解决方法
是否使用https://github.com/mongodb/mongo/blob/3cbb3eb/src/mongo/db/query/canonical_query.cpp#L346。
要返回任何坐标(联合)周围50公里范围内的所有文档:
db.collection.find(
{$or: [
{'location':{$geoWithin: {$centerSphere:[[ 72.50325, 23.01222 ], 50 / 6378.1]}}},
{'location':{$geoWithin: {$centerSphere:[[ 72.7788, 23.8787 ], 50 / 6378.1]}}}
]}
)
返回两个文件。
返回围绕所有坐标(十字路口)的半径50公里范围内的所有文件:
db.collection.find(
{$and: [
{'location':{$geoWithin: {$centerSphere:[[ 72.50325, 23.01222 ], 50 / 6378.1]}}},
{'location':{$geoWithin: {$centerSphere:[[ 72.7788, 23.8787 ], 50 / 6378.1]}}}
]}
)
不返回任何文档,因为它们都在自己的圆圈内,但是如果你增加距离,例如到500km:
db.collection.find(
{$and: [
{'location':{$geoWithin: {$centerSphere:[[ 72.50325, 23.01222 ], 500 / 6378.1]}}},
{'location':{$geoWithin: {$centerSphere:[[ 72.7788, 23.8787 ], 500 / 6378.1]}}}
]}
)
它将返回两个文件。
他们当然不会被分类。