您的位置:首页 > 编程语言 > Go语言

mogodb特点一:支持地理位置索引

2014-03-10 10:33 197 查看
mongoDB支持二维空间索引,使用空间索引,mongoDB支持一种特殊查询,如某地图网站上可以查找离你最近的咖啡厅,银行等信息。这个使用mongoDB的空间索引结合特殊的查询方法很容易实现。

前提条件:

建立空间索引的key可以使用array或内嵌文档存储,但是前两个elements必须存储固定的一对空间位置数值。如

{ loc : [ 50 , 30 ] }
{ loc : { x : 50 , y : 30 } }
{ loc : { foo : 50 , y : 30 } }
{ loc : { lat : 40.739037, long: 73.992964 } }

# 使用范例1:

> db.mapinfo.drop()                                        

true

> db.mapinfo.insert({"category" : "coffee","name" : "digoal coffee bar","loc" : [70,80]})

> db.mapinfo.insert({"category" : "tea","name" : "digoal tea bar","loc" : [70,80]})     

> db.mapinfo.insert({"category" : "tea","name" : "hangzhou tea bar","loc" : [71,81]})

> db.mapinfo.insert({"category" : "coffee","name" : "hangzhou coffee bar","loc" : [71,81]})

# 未创建2d索引时,不可以使用$near进行查询

> db.mapinfo.find({loc : {$near : [50,50]}})

error: {

        "$err" : "can't find special index: 2d for: { loc: { $near: [ 50.0, 50.0 ] } }",

        "code" : 13038

}

# 在loc上面创建2d索引

> db.mapinfo.ensureIndex({"loc" : "2d"},{"background" : true})

> db.mapinfo.getIndexes()                                    

[

        {

                "name" : "_id_",

                "ns" : "test.mapinfo",

                "key" : {

                        "_id" : 1

                }

        },

        {

                "_id" : ObjectId("4d242e1f3238ba30f9ca05ad"),

                "ns" : "test.mapinfo",

                "key" : {

                        "loc" : "2d"

                },

                "name" : "loc_",

                "background" : true

        }

]

# 查询测试,返回结果按照从最近到最远的顺序排序输出.

> db.mapinfo.find({loc : {$near : [72,82]},"category" : "coffee"}).explain()

{

        "cursor" : "GeoSearchCursor",

        "nscanned" : 2,

        "nscannedObjects" : 2,

        "n" : 2,

        "millis" : 0,

        "indexBounds" : {

        }

}

> db.mapinfo.find({loc : {$near : [72,82]},"category" : "coffee"})         

{ "_id" : ObjectId("4d242dce3238ba30f9ca05ac"), "category" : "coffee", "name" : "hangzhou coffee bar", "loc" : [ 71, 81 ] }

{ "_id" : ObjectId("4d242d8b3238ba30f9ca05a9"), "category" : "coffee", "name" : "digoal coffee bar", "loc" : [ 70, 80 ] }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: