【发布时间】:2014-06-27 00:46:21
【问题描述】:
这是我在这里的第一个问题,所以如果问得不好或者我的英语不好,请耐心等待。
我正在尝试在 Node.js 中的 MongoDB 中进行地理空间查询。
这个查询很好用
collection.find( { loc : { $geoWithin :
{ $centerSphere :
[ [ point.coordinates[0], point.coordinates[1]] , getRadiusMeters(radius) ]
} } } )
但是当我尝试对 $nearSphere 做同样的事情时:
collection.find( { loc :{ $nearSphere :
{ $geometry :
{ type : "Point" ,
coordinates : [ point.coordinates[0], point.coordinates[1]] } ,
$maxDistance : getRadiusMeters(radius)
} } } )
我收到以下错误:
{ [MongoError: can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { loc: { $nearSphere: { $geometry: { type: "Point", coordinates: [ 6.128777, 49.596792 ] }, $maxDistance: 10000 } } }] name: 'MongoError' }
我认为我有正确的索引。这是我的索引:
> db.realtrip.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.realtrip",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"loc" : "2dsphere"
},
"ns" : "test.realtrip",
"name" : "loc_2dsphere"
},
{
"v" : 1,
"key" : {
"tags" : 1
},
"ns" : "test.realtrip",
"name" : "tags_1"
},
{
"v" : 1,
"key" : {
"loc" : "2d"
},
"ns" : "test.realtrip",
"name" : "loc_2d"
}
]
我找不到我做错了什么。 $centerSphere 查询工作正常,只有 $nearSphere 查询给我错误。
【问题讨论】:
-
您在运行以下命令时是否遇到同样的错误?
collection.ensureIndex({loc: '2dsphere'}, function(err, result) { console.log(err); collection.geoNear(point.coordinates[0], point.coordinates[1], {spherical: true, maxDistance: getRadiusMeters(radius)}, function(err, docs) { console.log(err); }); }); -
我得到:null null 加上我的 mongodb 窗口中的以下内容:构建索引 realtrip.geo_data { loc: "2dsphere" } 构建索引完成。共扫描了 12932 条记录。 0.454 秒插入 realtrip.system.indexes ninserted:1 keyUpdates:0 locks(micros) w:489707 489ms
-
docs的值是多少?您是否从 MongoDB 获得任何文档? -
看起来这解决了索引的问题。 collection.geoNear 给了我一个距离数组。我的原始查询现在返回一个空数组,但我相信我现在可以让它工作。非常感谢
标签: node.js mongodb geospatial mongodb-query