这是我的第一个问题,因此,如果它的要求不是很好,或者我的英语不好,请耐心等待。

我正在尝试在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查询给我错误。

最佳答案

原来我的错误与这个问题有关Bugreport Mongodb

更新我的mongodb解决了它。现在,代码可以按预期工作。

09-27 20:26