Mongo DB:使用$ near查询时未找到任何结果

时间:2017-01-01 09:10:37

标签: spring mongodb mongodb-query geospatial

我使用Mongo DB存储坐标,我想使用$ near查询找到坐标,但我没有结果,有人可以帮助我吗? 这是我的mongo db索引

> db.course.getIndexes()
[
    {
            "v" : 1,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "dev.course"
    },
    {
            "v" : 1,
            "key" : {
                    "coordinate" : "2dsphere"
            },
            "name" : "coordinate_2dsphere",
            "ns" : "dev.course",
            "2dsphereIndexVersion" : 3
    }
]

这是我的数据

{ "_id" : 1,  "schoolId" : 0, "longitude" : 0, "latitude" : 0, "coordinate" : [ 0, 0 ], "courseTitle" : "暂无", "imageIds" : "[]", "videoIds" : "[]", "startTime" : "", "teacherIds" : "[]", "gradeIds" : "[]", "subjectId" : 0, "expense" : 0, "followNum" : 0, "courseStatus" : "NOSTART", "authorizationStatus" : "NO", "rejectReason" : "", "createTime" : "2017-01-01 16:58:22" }

我的查询是

db.course.find({"coordinate": {"near": [123, 20]}})

没有结果。有谁能够帮我?

1 个答案:

答案 0 :(得分:1)

$near是要使用的运算符,如果您编写near,它只会匹配near字段下名为coordinate的字段。

$near请求就像:

db.course.find({
    "coordinate": {
        "$near": {
            $geometry: {
                type: "Point",
                coordinates: [123, 20]
            }
        }
    }
})

要使用2dsphere索引,文档应为GeoJSON格式,且需要另外的type字段:

{ type: "<GeoJSON type>" , coordinates: <coordinates> }

因此,您只需要将"coordinate" : [ 0, 0 ]替换为:

"coordinate": {
    type: "Point",
    coordinates: [0, 0]
}